diff --git a/configs/mocha-config-devtools/package.json b/configs/mocha-config-devtools/package.json index 31d69def..afa33754 100644 --- a/configs/mocha-config-devtools/package.json +++ b/configs/mocha-config-devtools/package.json @@ -40,7 +40,7 @@ "jsdom": "^22.1.0", "react-16-node-hanging-test-fix": "^1.0.0", "sinon-chai": "^3.7.0", - "ts-node": "^10.9.1", + "ts-node": "^10.9.2", "why-is-node-running": "^2.2.2" } } diff --git a/package-lock.json b/package-lock.json index 1119e3b3..7d16d638 100644 --- a/package-lock.json +++ b/package-lock.json @@ -67,7 +67,7 @@ "jsdom": "^22.1.0", "react-16-node-hanging-test-fix": "^1.0.0", "sinon-chai": "^3.7.0", - "ts-node": "^10.9.1", + "ts-node": "^10.9.2", "why-is-node-running": "^2.2.2" }, "devDependencies": { @@ -3006,6 +3006,10 @@ "resolved": "configs/prettier-config-devtools", "link": true }, + "node_modules/@mongodb-js/query-parser": { + "resolved": "packages/query-parser", + "link": true + }, "node_modules/@mongodb-js/saslprep": { "resolved": "packages/saslprep", "link": true @@ -4154,16 +4158,15 @@ "dev": true }, "node_modules/@types/webidl-conversions": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.0.tgz", - "integrity": "sha512-xTE1E+YF4aWPJJeUzaZI5DRntlkY3+BCVJi0axFptnjGmAoWxkyREIh/XMrfxVLejwQxMCfDXdICo0VLxThrog==" + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==" }, "node_modules/@types/whatwg-url": { - "version": "8.2.2", - "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-8.2.2.tgz", - "integrity": "sha512-FtQu10RWgn3D9U4aazdwIE2yzphmTJREDqNdODHrbrZmmMqI0vMheC/6NE/J1Yveaj8H+ela+YwWTjq5PGmuhA==", + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.3.tgz", + "integrity": "sha512-z1ELvMijRL1QmU7QuzDkeYXSF2+dXI0ITKoQsIoVKcNBOiK5RMmWy+pYYxJTHFt8vkpZe7UsvRErQwcxZkjoUw==", "dependencies": { - "@types/node": "*", "@types/webidl-conversions": "*" } }, @@ -5487,11 +5490,11 @@ } }, "node_modules/bson": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/bson/-/bson-5.3.0.tgz", - "integrity": "sha512-ukmCZMneMlaC5ebPHXIkP8YJzNl5DC41N5MAIvKDqLggdao342t4McltoJBQfQya/nHBWAcSsYRqlXPoQkTJag==", + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.2.0.tgz", + "integrity": "sha512-ID1cI+7bazPDyL9wYy9GaQ8gEEohWvcUl/Yf0dIdutJxnmInEEyCsb4awy/OiBfall7zBA179Pahi3vCdFze3Q==", "engines": { - "node": ">=14.20.1" + "node": ">=16.20.1" } }, "node_modules/buffer": { @@ -6603,17 +6606,6 @@ "node": ">=14" } }, - "node_modules/data-urls/node_modules/tr46": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", - "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", - "dependencies": { - "punycode": "^2.3.0" - }, - "engines": { - "node": ">=14" - } - }, "node_modules/data-urls/node_modules/whatwg-url": { "version": "12.0.1", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-12.0.1.tgz", @@ -7304,6 +7296,31 @@ "node": ">=0.10.0" } }, + "node_modules/ejson-shell-parser": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ejson-shell-parser/-/ejson-shell-parser-2.0.0.tgz", + "integrity": "sha512-6JF9J7RCxHRikBi5u9qAAHA0LleY3DKamqH5vwMVjSnlNAQJGTxfgl3z16/G9bxH7xZnHOg4w0XSgnFzTQ2QCg==", + "dependencies": { + "acorn": "^8.1.0" + }, + "engines": { + "node": ">=16" + }, + "peerDependencies": { + "bson": "^4.6.3 || ^5 || ^6" + } + }, + "node_modules/ejson-shell-parser/node_modules/acorn": { + "version": "8.11.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", + "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/electron-to-chromium": { "version": "1.4.454", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.454.tgz", @@ -10295,6 +10312,11 @@ "node": ">=10" } }, + "node_modules/javascript-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/javascript-stringify/-/javascript-stringify-2.1.0.tgz", + "integrity": "sha512-JVAfqNPTvNq3sB/VHQJAFxN/sPgKnsKrCwyRt15zwNCdrMMJDdcEOdubuy+DuJYYdm0ox1J4uzEuYKkN+9yhVg==" + }, "node_modules/jest-diff": { "version": "29.5.0", "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.5.0.tgz", @@ -10467,17 +10489,6 @@ "node": ">=6" } }, - "node_modules/jsdom/node_modules/tr46": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", - "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", - "dependencies": { - "punycode": "^2.3.0" - }, - "engines": { - "node": ">=14" - } - }, "node_modules/jsdom/node_modules/universalify": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", @@ -13205,44 +13216,57 @@ } }, "node_modules/mongodb": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.6.0.tgz", - "integrity": "sha512-z8qVs9NfobHJm6uzK56XBZF8XwM9H294iRnB7wNjF0SnY93si5HPziIJn+qqvUR5QOff/4L0gCD6SShdR/GtVQ==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.3.0.tgz", + "integrity": "sha512-tt0KuGjGtLUhLoU263+xvQmPHEGTw5LbcNC73EoFRYgSHwZt5tsoJC110hDyO1kjQzpgNrpdcSza9PknWN4LrA==", "dependencies": { - "bson": "^5.3.0", - "mongodb-connection-string-url": "^2.6.0", - "socks": "^2.7.1" + "@mongodb-js/saslprep": "^1.1.0", + "bson": "^6.2.0", + "mongodb-connection-string-url": "^3.0.0" }, "engines": { - "node": ">=14.20.1" - }, - "optionalDependencies": { - "saslprep": "^1.0.3" + "node": ">=16.20.1" }, "peerDependencies": { - "@aws-sdk/credential-providers": "^3.201.0", - "mongodb-client-encryption": ">=2.3.0 <3", - "snappy": "^7.2.2" + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" }, "peerDependenciesMeta": { "@aws-sdk/credential-providers": { "optional": true }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, "mongodb-client-encryption": { "optional": true }, "snappy": { "optional": true + }, + "socks": { + "optional": true } } }, "node_modules/mongodb-connection-string-url": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.6.0.tgz", - "integrity": "sha512-WvTZlI9ab0QYtTYnuMLgobULWhokRjtC7db9LtcVfJ+Hsnyr5eo6ZtNAt3Ly24XZScGMelOcGtm7lSn0332tPQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.0.tgz", + "integrity": "sha512-t1Vf+m1I5hC2M5RJx/7AtxgABy1cZmIPQRMXw+gEIPn/cZNF3Oiy+l0UIypUwVB5trcWHq3crg2g3uAR9aAwsQ==", "dependencies": { - "@types/whatwg-url": "^8.2.1", - "whatwg-url": "^11.0.0" + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" } }, "node_modules/mongodb-download-url": { @@ -16468,18 +16492,6 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, - "node_modules/saslprep": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", - "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", - "optional": true, - "dependencies": { - "sparse-bitfield": "^3.0.3" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/sass": { "version": "1.54.0", "resolved": "https://registry.npmjs.org/sass/-/sass-1.54.0.tgz", @@ -17620,14 +17632,14 @@ } }, "node_modules/tr46": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", - "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", "dependencies": { - "punycode": "^2.1.1" + "punycode": "^2.3.0" }, "engines": { - "node": ">=12" + "node": ">=14" } }, "node_modules/traverse": { @@ -17654,9 +17666,9 @@ } }, "node_modules/ts-node": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", - "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", "dependencies": { "@cspotcode/source-map-support": "^0.8.0", "@tsconfig/node10": "^1.0.7", @@ -18301,15 +18313,15 @@ } }, "node_modules/whatwg-url": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", - "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", "dependencies": { - "tr46": "^3.0.0", + "tr46": "^4.1.1", "webidl-conversions": "^7.0.0" }, "engines": { - "node": ">=12" + "node": ">=16" } }, "node_modules/which": { @@ -19115,8 +19127,9 @@ "license": "Apache-2.0", "dependencies": { "@mongodb-js/mongodb-downloader": "^0.2.9", + "@mongodb-js/saslprep": "^1.1.1", "debug": "^4.3.4", - "mongodb": "^5.6.0", + "mongodb": "^6.3.0", "mongodb-connection-string-url": "^3.0.0", "yargs": "^17.7.2" }, @@ -19145,14 +19158,6 @@ "typescript": "^5.0.4" } }, - "packages/mongodb-runner/node_modules/@types/whatwg-url": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.3.tgz", - "integrity": "sha512-z1ELvMijRL1QmU7QuzDkeYXSF2+dXI0ITKoQsIoVKcNBOiK5RMmWy+pYYxJTHFt8vkpZe7UsvRErQwcxZkjoUw==", - "dependencies": { - "@types/webidl-conversions": "*" - } - }, "packages/mongodb-runner/node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -19166,26 +19171,6 @@ "node": ">=12" } }, - "packages/mongodb-runner/node_modules/mongodb-connection-string-url": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.0.tgz", - "integrity": "sha512-t1Vf+m1I5hC2M5RJx/7AtxgABy1cZmIPQRMXw+gEIPn/cZNF3Oiy+l0UIypUwVB5trcWHq3crg2g3uAR9aAwsQ==", - "dependencies": { - "@types/whatwg-url": "^11.0.2", - "whatwg-url": "^13.0.0" - } - }, - "packages/mongodb-runner/node_modules/tr46": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", - "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", - "dependencies": { - "punycode": "^2.3.0" - }, - "engines": { - "node": ">=14" - } - }, "packages/mongodb-runner/node_modules/typescript": { "version": "5.1.6", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz", @@ -19199,18 +19184,6 @@ "node": ">=14.17" } }, - "packages/mongodb-runner/node_modules/whatwg-url": { - "version": "13.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", - "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", - "dependencies": { - "tr46": "^4.1.1", - "webidl-conversions": "^7.0.0" - }, - "engines": { - "node": ">=16" - } - }, "packages/mongodb-runner/node_modules/yargs": { "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", @@ -19510,6 +19483,49 @@ "node": ">=12" } }, + "packages/query-parser": { + "name": "@mongodb-js/query-parser", + "version": "4.0.0", + "license": "Apache-2.0", + "dependencies": { + "debug": "^4.3.4", + "ejson-shell-parser": "^2.0.0", + "javascript-stringify": "^2.1.0", + "lodash": "^4.17.21" + }, + "devDependencies": { + "@mongodb-js/eslint-config-devtools": "0.9.10", + "@mongodb-js/mocha-config-devtools": "^1.0.2", + "@mongodb-js/prettier-config-devtools": "^1.0.1", + "@mongodb-js/tsconfig-devtools": "^1.0.1", + "@types/chai": "^4.2.21", + "@types/mocha": "^9.0.0", + "@types/node": "^17.0.35", + "@types/sinon-chai": "^3.2.5", + "bson": "^6.2.0", + "depcheck": "^1.4.1", + "eslint": "^7.25.0", + "gen-esm-wrapper": "^1.1.0", + "mocha": "^8.4.0", + "nyc": "^15.1.0", + "prettier": "^2.3.2", + "sinon": "^9.2.3", + "typescript": "^5.0.4" + } + }, + "packages/query-parser/node_modules/typescript": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", + "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, "packages/saslprep": { "name": "@mongodb-js/saslprep", "version": "1.1.2", @@ -21937,7 +21953,7 @@ "react": ">=16", "react-16-node-hanging-test-fix": "^1.0.0", "sinon-chai": "^3.7.0", - "ts-node": "^10.9.1", + "ts-node": "^10.9.2", "why-is-node-running": "^2.2.2" }, "dependencies": { @@ -22275,6 +22291,40 @@ } } }, + "@mongodb-js/query-parser": { + "version": "file:packages/query-parser", + "requires": { + "@mongodb-js/eslint-config-devtools": "0.9.10", + "@mongodb-js/mocha-config-devtools": "^1.0.2", + "@mongodb-js/prettier-config-devtools": "^1.0.1", + "@mongodb-js/tsconfig-devtools": "^1.0.1", + "@types/chai": "^4.2.21", + "@types/mocha": "^9.0.0", + "@types/node": "^17.0.35", + "@types/sinon-chai": "^3.2.5", + "bson": "^6.2.0", + "debug": "^4.3.4", + "depcheck": "^1.4.1", + "ejson-shell-parser": "^2.0.0", + "eslint": "^7.25.0", + "gen-esm-wrapper": "^1.1.0", + "javascript-stringify": "^2.1.0", + "lodash": "^4.17.21", + "mocha": "^8.4.0", + "nyc": "^15.1.0", + "prettier": "^2.3.2", + "sinon": "^9.2.3", + "typescript": "^5.0.4" + }, + "dependencies": { + "typescript": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", + "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", + "dev": true + } + } + }, "@mongodb-js/saslprep": { "version": "file:packages/saslprep", "requires": { @@ -23381,16 +23431,15 @@ "dev": true }, "@types/webidl-conversions": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.0.tgz", - "integrity": "sha512-xTE1E+YF4aWPJJeUzaZI5DRntlkY3+BCVJi0axFptnjGmAoWxkyREIh/XMrfxVLejwQxMCfDXdICo0VLxThrog==" + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==" }, "@types/whatwg-url": { - "version": "8.2.2", - "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-8.2.2.tgz", - "integrity": "sha512-FtQu10RWgn3D9U4aazdwIE2yzphmTJREDqNdODHrbrZmmMqI0vMheC/6NE/J1Yveaj8H+ela+YwWTjq5PGmuhA==", + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.3.tgz", + "integrity": "sha512-z1ELvMijRL1QmU7QuzDkeYXSF2+dXI0ITKoQsIoVKcNBOiK5RMmWy+pYYxJTHFt8vkpZe7UsvRErQwcxZkjoUw==", "requires": { - "@types/node": "*", "@types/webidl-conversions": "*" } }, @@ -24413,9 +24462,9 @@ } }, "bson": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/bson/-/bson-5.3.0.tgz", - "integrity": "sha512-ukmCZMneMlaC5ebPHXIkP8YJzNl5DC41N5MAIvKDqLggdao342t4McltoJBQfQya/nHBWAcSsYRqlXPoQkTJag==" + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.2.0.tgz", + "integrity": "sha512-ID1cI+7bazPDyL9wYy9GaQ8gEEohWvcUl/Yf0dIdutJxnmInEEyCsb4awy/OiBfall7zBA179Pahi3vCdFze3Q==" }, "buffer": { "version": "5.7.1", @@ -25248,14 +25297,6 @@ "whatwg-url": "^12.0.0" }, "dependencies": { - "tr46": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", - "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", - "requires": { - "punycode": "^2.3.0" - } - }, "whatwg-url": { "version": "12.0.1", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-12.0.1.tgz", @@ -25777,6 +25818,21 @@ "jake": "^10.8.5" } }, + "ejson-shell-parser": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ejson-shell-parser/-/ejson-shell-parser-2.0.0.tgz", + "integrity": "sha512-6JF9J7RCxHRikBi5u9qAAHA0LleY3DKamqH5vwMVjSnlNAQJGTxfgl3z16/G9bxH7xZnHOg4w0XSgnFzTQ2QCg==", + "requires": { + "acorn": "^8.1.0" + }, + "dependencies": { + "acorn": { + "version": "8.11.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", + "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==" + } + } + }, "electron-to-chromium": { "version": "1.4.454", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.454.tgz", @@ -27994,6 +28050,11 @@ "minimatch": "^3.1.2" } }, + "javascript-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/javascript-stringify/-/javascript-stringify-2.1.0.tgz", + "integrity": "sha512-JVAfqNPTvNq3sB/VHQJAFxN/sPgKnsKrCwyRt15zwNCdrMMJDdcEOdubuy+DuJYYdm0ox1J4uzEuYKkN+9yhVg==" + }, "jest-diff": { "version": "29.5.0", "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.5.0.tgz", @@ -28124,14 +28185,6 @@ "url-parse": "^1.5.3" } }, - "tr46": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", - "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", - "requires": { - "punycode": "^2.3.0" - } - }, "universalify": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", @@ -30257,23 +30310,22 @@ "dev": true }, "mongodb": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.6.0.tgz", - "integrity": "sha512-z8qVs9NfobHJm6uzK56XBZF8XwM9H294iRnB7wNjF0SnY93si5HPziIJn+qqvUR5QOff/4L0gCD6SShdR/GtVQ==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.3.0.tgz", + "integrity": "sha512-tt0KuGjGtLUhLoU263+xvQmPHEGTw5LbcNC73EoFRYgSHwZt5tsoJC110hDyO1kjQzpgNrpdcSza9PknWN4LrA==", "requires": { - "bson": "^5.3.0", - "mongodb-connection-string-url": "^2.6.0", - "saslprep": "^1.0.3", - "socks": "^2.7.1" + "@mongodb-js/saslprep": "^1.1.0", + "bson": "^6.2.0", + "mongodb-connection-string-url": "^3.0.0" } }, "mongodb-connection-string-url": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.6.0.tgz", - "integrity": "sha512-WvTZlI9ab0QYtTYnuMLgobULWhokRjtC7db9LtcVfJ+Hsnyr5eo6ZtNAt3Ly24XZScGMelOcGtm7lSn0332tPQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.0.tgz", + "integrity": "sha512-t1Vf+m1I5hC2M5RJx/7AtxgABy1cZmIPQRMXw+gEIPn/cZNF3Oiy+l0UIypUwVB5trcWHq3crg2g3uAR9aAwsQ==", "requires": { - "@types/whatwg-url": "^8.2.1", - "whatwg-url": "^11.0.0" + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" } }, "mongodb-download-url": { @@ -30304,6 +30356,7 @@ "@mongodb-js/mocha-config-devtools": "^1.0.2", "@mongodb-js/mongodb-downloader": "^0.2.9", "@mongodb-js/prettier-config-devtools": "^1.0.1", + "@mongodb-js/saslprep": "^1.1.1", "@mongodb-js/tsconfig-devtools": "^1.0.1", "@types/chai": "^4.2.21", "@types/debug": "^4.1.8", @@ -30317,7 +30370,7 @@ "eslint": "^7.25.0", "gen-esm-wrapper": "^1.1.0", "mocha": "^8.4.0", - "mongodb": "^5.6.0", + "mongodb": "^6.3.0", "mongodb-connection-string-url": "^3.0.0", "nyc": "^15.1.0", "prettier": "2.3.2", @@ -30326,14 +30379,6 @@ "yargs": "^17.7.2" }, "dependencies": { - "@types/whatwg-url": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.3.tgz", - "integrity": "sha512-z1ELvMijRL1QmU7QuzDkeYXSF2+dXI0ITKoQsIoVKcNBOiK5RMmWy+pYYxJTHFt8vkpZe7UsvRErQwcxZkjoUw==", - "requires": { - "@types/webidl-conversions": "*" - } - }, "cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -30344,38 +30389,12 @@ "wrap-ansi": "^7.0.0" } }, - "mongodb-connection-string-url": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.0.tgz", - "integrity": "sha512-t1Vf+m1I5hC2M5RJx/7AtxgABy1cZmIPQRMXw+gEIPn/cZNF3Oiy+l0UIypUwVB5trcWHq3crg2g3uAR9aAwsQ==", - "requires": { - "@types/whatwg-url": "^11.0.2", - "whatwg-url": "^13.0.0" - } - }, - "tr46": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", - "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", - "requires": { - "punycode": "^2.3.0" - } - }, "typescript": { "version": "5.1.6", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz", "integrity": "sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==", "dev": true }, - "whatwg-url": { - "version": "13.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", - "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", - "requires": { - "tr46": "^4.1.1", - "webidl-conversions": "^7.0.0" - } - }, "yargs": { "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", @@ -32809,15 +32828,6 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, - "saslprep": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", - "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", - "optional": true, - "requires": { - "sparse-bitfield": "^3.0.3" - } - }, "sass": { "version": "1.54.0", "resolved": "https://registry.npmjs.org/sass/-/sass-1.54.0.tgz", @@ -33720,11 +33730,11 @@ } }, "tr46": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", - "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", "requires": { - "punycode": "^2.1.1" + "punycode": "^2.3.0" } }, "traverse": { @@ -33745,9 +33755,9 @@ "dev": true }, "ts-node": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", - "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", "requires": { "@cspotcode/source-map-support": "^0.8.0", "@tsconfig/node10": "^1.0.7", @@ -34224,11 +34234,11 @@ "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==" }, "whatwg-url": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", - "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", "requires": { - "tr46": "^3.0.0", + "tr46": "^4.1.1", "webidl-conversions": "^7.0.0" } }, diff --git a/packages/mongodb-runner/.depcheckrc b/packages/mongodb-runner/.depcheckrc index 48bf9af6..409742d5 100644 --- a/packages/mongodb-runner/.depcheckrc +++ b/packages/mongodb-runner/.depcheckrc @@ -1,8 +1,11 @@ ignores: - - '@mongodb-js/prettier-config-devtools' - - '@mongodb-js/tsconfig-devtools' - - '@types/chai' - - '@types/sinon-chai' - - 'sinon' + - '@mongodb-js/prettier-config-devtools' + - '@mongodb-js/tsconfig-devtools' + - '@types/chai' + - '@types/sinon-chai' + - 'sinon' + # this is explicitly called as a dependency to make sure that is bootstrapped + # before mongodb-runner, since it is required via mongodb + - '@mongodb-js/saslprep' ignore-patterns: - - 'dist' + - 'dist' diff --git a/packages/mongodb-runner/package.json b/packages/mongodb-runner/package.json index 9de0f802..c83ce3ff 100644 --- a/packages/mongodb-runner/package.json +++ b/packages/mongodb-runner/package.json @@ -52,7 +52,8 @@ "dependencies": { "@mongodb-js/mongodb-downloader": "^0.2.9", "debug": "^4.3.4", - "mongodb": "^5.6.0", + "mongodb": "^6.3.0", + "@mongodb-js/saslprep": "^1.1.1", "mongodb-connection-string-url": "^3.0.0", "yargs": "^17.7.2" }, diff --git a/packages/query-parser/.depcheckrc b/packages/query-parser/.depcheckrc new file mode 100644 index 00000000..48bf9af6 --- /dev/null +++ b/packages/query-parser/.depcheckrc @@ -0,0 +1,8 @@ +ignores: + - '@mongodb-js/prettier-config-devtools' + - '@mongodb-js/tsconfig-devtools' + - '@types/chai' + - '@types/sinon-chai' + - 'sinon' +ignore-patterns: + - 'dist' diff --git a/packages/query-parser/.eslintignore b/packages/query-parser/.eslintignore new file mode 100644 index 00000000..85a8a75e --- /dev/null +++ b/packages/query-parser/.eslintignore @@ -0,0 +1,2 @@ +.nyc-output +dist diff --git a/packages/query-parser/.eslintrc.js b/packages/query-parser/.eslintrc.js new file mode 100644 index 00000000..83296d73 --- /dev/null +++ b/packages/query-parser/.eslintrc.js @@ -0,0 +1,8 @@ +module.exports = { + root: true, + extends: ['@mongodb-js/eslint-config-devtools'], + parserOptions: { + tsconfigRootDir: __dirname, + project: ['./tsconfig-lint.json'], + }, +}; diff --git a/packages/query-parser/.mocharc.js b/packages/query-parser/.mocharc.js new file mode 100644 index 00000000..64afeb1f --- /dev/null +++ b/packages/query-parser/.mocharc.js @@ -0,0 +1 @@ +module.exports = require('@mongodb-js/mocha-config-devtools'); diff --git a/packages/query-parser/.prettierignore b/packages/query-parser/.prettierignore new file mode 100644 index 00000000..4d28df66 --- /dev/null +++ b/packages/query-parser/.prettierignore @@ -0,0 +1,3 @@ +.nyc_output +dist +coverage diff --git a/packages/query-parser/.prettierrc.json b/packages/query-parser/.prettierrc.json new file mode 100644 index 00000000..dfae21d0 --- /dev/null +++ b/packages/query-parser/.prettierrc.json @@ -0,0 +1 @@ +"@mongodb-js/prettier-config-devtools" diff --git a/packages/query-parser/LICENSE b/packages/query-parser/LICENSE new file mode 100644 index 00000000..5e0fd33c --- /dev/null +++ b/packages/query-parser/LICENSE @@ -0,0 +1,201 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or +Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices +stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works +that You distribute, all copyright, patent, trademark, and +attribution notices from the Source form of the Work, +excluding those notices that do not pertain to any part of +the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its +distribution, then any Derivative Works that You distribute must +include a readable copy of the attribution notices contained +within such NOTICE file, excluding those notices that do not +pertain to any part of the Derivative Works, in at least one +of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or +documentation, if provided along with the Derivative Works; or, +within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and +do not modify the License. You may add Your own attribution +notices within Derivative Works that You distribute, alongside +or as an addendum to the NOTICE text from the Work, provided +that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following +boilerplate notice, with the fields enclosed by brackets "{}" +replaced with your own identifying information. (Don't include +the brackets!) The text should be enclosed in the appropriate +comment syntax for the file format. We also recommend that a +file or class name and description of purpose be included on the +same "printed page" as the copyright notice for easier +identification within third-party archives. + +Copyright {yyyy} {name of copyright owner} + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/packages/query-parser/MIGRATION.md b/packages/query-parser/MIGRATION.md new file mode 100644 index 00000000..2009391e --- /dev/null +++ b/packages/query-parser/MIGRATION.md @@ -0,0 +1,77 @@ +# Migration Guide + +MongoDB Query Parser will attempt to minimise API changes between major versions. However, as part of our process to constantly improve security and keep packages up to date, backwards breaking changes can and will occur. + +This is a guide to help you make the switch when this happens. + +## Table Of Contents + +- [Migrating from 1.0 to 2.0](#migrating-from-10-to-20) + +## Migrating from 1.0 to 2.0 + +This major version includes two big changes: + +- [Updating the version of BSON from v1 to v4](#JS-BSON-breaking-changes) +- [Changing what types of MQL expressions are allowed in the query parser](#restricting-MQL-expressions) + +### JS-BSON Breaking Changes + +Please refer to [the list of BSON changes](https://github.com/mongodb/js-bson/blob/master/HISTORY.md), as well as the [upgrade documentation for v4](https://github.com/mongodb/js-bson/blob/master/docs/upgrade-to-v4.md) for more information, but breaking changes that have occurred as part of this upgrade are: + +- **`ObjectId`** will now throw TypeErrors instead of silently erroring with invalid input +- **`Symbol`** has now been renamed to **`BSONSymbol`** as it was conflicting with the ES6 **`Symbol`** type +- BSON-JS now relies on Node.js v6 or above, and uses ES2015 features in non-transpiled code +- All BSON types are now ES6 Classes +- Long is now backed by `Long.js` + +### Restricting MQL expressions + +MongoDB Query Parser was making use of [`safer-eval`](https://www.npmjs.com/package/safer-eval) to parse difficult queries, which has been removed as this dependency is insecure. + +We've replaced this dependency with [`ejson-shell-parser`](https://github.com/mongodb-js/ejson-shell-parser), which instead walks the AST of the query, and only attempts to evaluate the query if it considered safe and well-formed. + +Because of this change, some queries that would validate are no longer valid. + +Expressions that will now **fail** include: + +- Function declarations (both `function` and lambdas) +- Ternary syntax (`y > 5 ? 'yes' : 'no'`) +- Comma syntax (`const a = 5, 3`) +- Variable assignment (`{ a: (c = 5, c)}`) + +As a result, queries like this will no longer be accepted as valid input: + +```javascript +{ + ternary: true ? 2 : 3, + commaOperator: ("doesn't work", "as users expect"), + functionDeclaration: (function(d) { return d.setMonth(0) })(new Date()), + variableAssignment: (d = new Date(), d.setDate(1), d), +} +``` + +However, we now officially support these use-cases: + +- Simple expressions (`+`, `-`, `/`, `!` etc) +- Method from Math (excluding `random`) +- Methods on Date (including `.now()`) +- Comments (both `//` and `/* */`) + +This means you can build an MQL expression like so: + +```javascript +{ + // Calculates the day for the current year (Jan 1 = 1, Feb 1 = 32) + dayOfYear: Math.round((new Date().setHours(23) - new Date(new Date().getFullYear(), 0, 1, 0, 0, 0))/1000/60/60/24), + now: Date.now(), + symbol: BSONSymbol('Example Symbol') +} +``` + +As part of this change, error messages that are produced will be slightly different. While it'll still throw a `SyntaxError`, we now return the coordinates of the incorrect token, instead of just what token was incorrect. + +```javascript +eval('({a: )'); // SyntaxError: Unexpected token ')' +parseProject('({a: )'); // SyntaxError: Unexpected token (1:5) +``` diff --git a/packages/query-parser/README.md b/packages/query-parser/README.md new file mode 100644 index 00000000..c3a692b6 --- /dev/null +++ b/packages/query-parser/README.md @@ -0,0 +1,67 @@ +# mongodb-query-parser [![Check and Test][workflow_img]][workflow_url] [![npm][npm_img]][npm_url] + +> Safe parsing and validation for MongoDB queries (filters), projections, and more. + +## Example + +Turn some JS code as a string into a real JS object safely and with no bson type loss: + +```javascript +require('mongodb-query-parser')('{_id: ObjectId("58c33a794d08b991e3648fd2")}'); +// >>> {_id: ObjectId('58c33a794d08b991e3648fd2'x)} +``` + +### Usage with codemirror + +```javascript +var parser = require('mongodb-query-parser'); +var query = '{_id: ObjectId("58c33a794d08b991e3648fd2")}'; +// What is this highlighting/language mode for this string? +parser.detect(query); +// >>> `javascript` + +var queryAsJSON = '{"_id":{"$oid":"58c33a794d08b991e3648fd2"}}'; +// What is this highlighting/language mode for this string? +parser.detect(queryAsJSON); +// >>> `json` + +// Turn it into a JS string that looks pretty in codemirror: +parser.toJavascriptString(parse(query)); +// >>> '{_id:ObjectId(\'58c33a794d08b991e3648fd2\')}' +``` + +### Extended JSON Support + +```javascript +var bson = require('bson'); +var parser = require('mongodb-query-parser'); +var queryAsAnObjectWithTypes = parser.parseFilter(query); + +// Use extended json to prove types are intact +bson.EJSON.stringify(queryAsAnObjectWithTypes); +// >>> '{"_id":{"$oid":"58c33a794d08b991e3648fd2"}}' + +var queryAsJSON = '{"_id":{"$oid":"58c33a794d08b991e3648fd2"}}'; +parser.detect(queryAsJSON); +// >>> `json` +``` + +## Migrations + +We aim to not have any API breaking changes in this library as we consider it stable, but breakages may occur whenever we upgrade a core dependency or perform a major refactor. + +We have a [migration guide](MIGRATION.md) which covers what to look out for between releases. + +## Related + +- [`mongodb-stage-validator`](https://github.com/mongodb-js/stage-validator) Parse and validate MongoDB Aggregation Pipeline stages. +- [`@mongodb-js/compass-query-bar`](https://github.com/mongodb-js/compass-query-bar) Compass UI Plugin that uses `mongodb-query-parser` for validation. + +## License + +Apache 2.0 + +[workflow_img]: https://github.com/mongodb-js/query-parser/workflows/Check%20and%20Test/badge.svg?event=push +[workflow_url]: https://github.com/mongodb-js/query-parser/actions?query=workflow%3A%22Check+and+Test%22 +[npm_img]: https://img.shields.io/npm/v/mongodb-query-parser.svg +[npm_url]: https://npmjs.org/package/mongodb-query-parser diff --git a/packages/query-parser/package.json b/packages/query-parser/package.json new file mode 100644 index 00000000..f4dfa90f --- /dev/null +++ b/packages/query-parser/package.json @@ -0,0 +1,73 @@ +{ + "name": "@mongodb-js/query-parser", + "description": "Parse MongoDB queries", + "author": { + "name": "MongoDB Inc", + "email": "compass@mongodb.com" + }, + "publishConfig": { + "access": "public" + }, + "bugs": { + "url": "https://jira.mongodb.org/projects/COMPASS/issues", + "email": "compass@mongodb.com" + }, + "homepage": "https://github.com/mongodb-js/devtools-shared", + "version": "4.0.0", + "repository": { + "type": "git", + "url": "https://github.com/mongodb-js/devtools-shared.git" + }, + "files": [ + "dist" + ], + "license": "Apache-2.0", + "main": "dist/index.js", + "exports": { + "require": "./dist/index.js", + "import": "./dist/.esm-wrapper.mjs" + }, + "types": "./dist/index.d.ts", + "scripts": { + "bootstrap": "npm run compile", + "prepublishOnly": "npm run compile", + "compile": "tsc -p tsconfig.json && gen-esm-wrapper . ./dist/.esm-wrapper.mjs", + "typecheck": "tsc --noEmit", + "eslint": "eslint", + "prettier": "prettier", + "lint": "npm run eslint . && npm run prettier -- --check .", + "depcheck": "depcheck", + "check": "npm run typecheck && npm run lint && npm run depcheck", + "check-ci": "npm run check", + "test": "mocha", + "test-cov": "nyc -x \"**/*.spec.*\" --reporter=lcov --reporter=text --reporter=html npm run test", + "test-watch": "npm run test -- --watch", + "test-ci": "npm run test-cov", + "reformat": "npm run prettier -- --write ." + }, + "dependencies": { + "debug": "^4.3.4", + "ejson-shell-parser": "^2.0.0", + "javascript-stringify": "^2.1.0", + "lodash": "^4.17.21" + }, + "devDependencies": { + "@mongodb-js/eslint-config-devtools": "0.9.10", + "@mongodb-js/mocha-config-devtools": "^1.0.2", + "@mongodb-js/prettier-config-devtools": "^1.0.1", + "@mongodb-js/tsconfig-devtools": "^1.0.1", + "@types/chai": "^4.2.21", + "@types/mocha": "^9.0.0", + "@types/node": "^17.0.35", + "@types/sinon-chai": "^3.2.5", + "bson": "^6.2.0", + "depcheck": "^1.4.1", + "eslint": "^7.25.0", + "gen-esm-wrapper": "^1.1.0", + "mocha": "^8.4.0", + "nyc": "^15.1.0", + "prettier": "^2.3.2", + "sinon": "^9.2.3", + "typescript": "^5.0.4" + } +} diff --git a/packages/query-parser/src/constants.ts b/packages/query-parser/src/constants.ts new file mode 100644 index 00000000..20cd63e5 --- /dev/null +++ b/packages/query-parser/src/constants.ts @@ -0,0 +1,169 @@ +const COLLATION_OPTIONS: { + [collationOption: string]: (string | number | boolean)[]; +} = { + locale: [ + 'af', + 'sq', + 'am', + 'ar', + 'ar@collation=compat', + 'hy', + 'as', + 'az', + 'az@collation=search', + 'be', + 'bn', + 'bn@collation=traditional', + 'bs', + 'bs@collation=search', + 'bs_Cyrl', + 'bg', + 'my', + 'ca', + 'ca@collation=search', + 'chr', + 'zh', + 'zh@collation=big5han', + 'zh@collation=gb2312han', + 'zh@collation=pinyin', + 'zh@collation=unihan', + 'zh@collation=zhuyin', + 'zh_Hant', + 'zh_Hant@collation=stroke', + 'hr', + 'hr@collation=search', + 'cs', + 'cs@collation=search', + 'da', + 'da@collation=search', + 'nl', + 'dz', + 'en', + 'en_US', + 'en_US_POSIX', + 'eo', + 'et', + 'ee', + 'fo', + 'fil', + 'fi_FI', + 'fi_FI@collation=search', + 'fi_FI@collation=traditional', + 'fr', + 'fr_CA', + 'gl', + 'gl@collation=search', + 'ka', + 'de', + 'de@collation=search', + 'de@collation=eor', + 'de@collation=phonebook', + 'de_AT', + 'de_AT@collation=phonebook', + 'el', + 'gu', + 'ha', + 'haw', + 'he', + 'he@collation=search', + 'hi', + 'hu', + 'is', + 'is@collation=search', + 'ig', + 'smn', + 'smn@collation=search', + 'id', + 'ga', + 'it', + 'ja', + 'ja@collation=unihan', + 'kl', + 'kl@collation=search', + 'kn', + 'kn@collation=traditional', + 'kk', + 'km', + 'kok', + 'ko', + 'ko@collation=search', + 'ko@collation=searchjl', + 'ko@collation=unihan', + 'ky', + 'lk', + 'lo', + 'lv', + 'li', + 'li@collation=phonetic', + 'lt', + 'dsb', + 'lb', + 'mk', + 'ms', + 'ml', + 'mt', + 'mr', + 'mn', + 'ne', + 'se', + 'se@collation=search', + 'nb', + 'nb@collation=search', + 'nn', + 'nn@collation=search', + 'or', + 'om', + 'ps', + 'fa', + 'fa_AF', + 'pl', + 'pt', + 'pa', + 'ro', + 'ru', + 'sr', + 'sr_Latn', + 'sr_Latn@collation=search', + 'si', + 'si@collation=dictionary', + 'sk', + 'sk@collation=search', + 'sl', + 'es', + 'es@collation=search', + 'es@collation=traditional', + 'sw', + 'sv', + 'sv@collation=search', + 'ta', + 'te', + 'th', + 'bo', + 'to', + 'tr', + 'tr@collation=search', + 'uk', + 'hsb', + 'ur', + 'ug', + 'vi', + 'vi@collation=traditional', + 'wae', + 'cy', + 'yi', + 'yi@collation=search', + 'yo', + 'zu', + 'simple', + ], + strength: [1, 2, 3, 4, 5], + caseLevel: [true, false], + caseFirst: ['upper', 'lower', 'off'], + numericOrdering: [true, false], + alternate: ['non-ignorable', 'shifted'], + maxVariable: [true, false], + backwards: [true, false], + normalization: [true, false], +}; + +export { COLLATION_OPTIONS }; diff --git a/packages/query-parser/src/index.spec.ts b/packages/query-parser/src/index.spec.ts new file mode 100644 index 00000000..8de6d22f --- /dev/null +++ b/packages/query-parser/src/index.spec.ts @@ -0,0 +1,613 @@ +import assert from 'assert'; +import sinon from 'sinon'; +import bson from 'bson'; +import _debug from 'debug'; + +import { + isCollationValid, + isFilterValid, + isLimitValid, + isMaxTimeMSValid, + isProjectValid, + isSkipValid, + isSortValid, + parseCollation, + parseFilter, + parseProject, + parseSort, + stringify, + DEFAULT_LIMIT, + DEFAULT_MAX_TIME_MS, + DEFAULT_SKIP, + validate, +} from './index'; + +const debug = _debug('mongodb-query-parser:test'); + +function convert(string: string) { + const res = parseFilter(string); + const ret = bson.EJSON.serialize(res, { legacy: true, relaxed: false }); + debug('converted', { input: string, parsed: res, encoded: ret }); + return ret; +} + +describe('mongodb-query-parser', function () { + describe('filter', function () { + context('when no new keyword is provided', function () { + it('returns the filter', function () { + const res = parseFilter('{_id: ObjectId("58c33a794d08b991e3648fd2")}'); + assert.deepEqual(res, { + _id: new bson.ObjectId('58c33a794d08b991e3648fd2'), + }); + }); + }); + + context('when a new keyword is provided', function () { + it('returns the filter', function () { + const res = parseFilter( + '{_id: new ObjectId("58c33a794d08b991e3648fd2")}' + ); + assert.deepEqual(res, { + _id: new bson.ObjectId('58c33a794d08b991e3648fd2'), + }); + }); + }); + + describe('shell helpers', function () { + it('should support Code', function () { + assert.deepEqual(convert('Code("return true", {})'), { + $code: 'return true', + $scope: {}, + }); + }); + + it('should support new Date', function () { + assert.deepEqual(convert('new Date("2017-01-01T12:35:31.123Z")'), { + $date: '2017-01-01T12:35:31.123Z', + }); + }); + + it('should support new Date (0 ms)', function () { + assert.deepEqual(convert('new Date("2017-01-01T12:35:31.000Z")'), { + $date: '2017-01-01T12:35:31Z', + }); + }); + + it('should support ISODate', function () { + assert.deepEqual(convert('ISODate("2017-01-01T12:35:31.123Z")'), { + $date: '2017-01-01T12:35:31.123Z', + }); + }); + + it('should support ISODate (0 ms)', function () { + assert.deepEqual(convert('ISODate("2017-01-01T12:35:31.000Z")'), { + $date: '2017-01-01T12:35:31Z', + }); + }); + + it('should support new ISODate', function () { + assert.deepEqual(convert('new ISODate("2017-01-01T12:35:31.123Z")'), { + $date: '2017-01-01T12:35:31.123Z', + }); + }); + + it('should support new ISODate (0 ms)', function () { + assert.deepEqual(convert('new ISODate("2017-01-01T12:35:31.000Z")'), { + $date: '2017-01-01T12:35:31Z', + }); + }); + + it('should support BinData', function () { + assert.deepEqual( + convert( + `new BinData(${bson.Binary.SUBTYPE_BYTE_ARRAY}, "OyQRAeK7QlWMr0E2xWapYg==")` + ), + { + $binary: 'OyQRAeK7QlWMr0E2xWapYg==', + $type: `0${bson.Binary.SUBTYPE_BYTE_ARRAY}`, + } + ); + }); + + it('should support UUID', function () { + assert.deepEqual( + convert('UUID("3b241101-e2bb-4255-8caf-4136c566a962")'), + { + $binary: 'OyQRAeK7QlWMr0E2xWapYg==', + $type: `0${bson.Binary.SUBTYPE_UUID}`, + } + ); + }); + + it('should support functions', function () { + assert.deepEqual(convert('{$match: () => true}'), { + $match: '() => true', + }); + + assert.deepEqual( + convert( + `{ + $expr: { + $function: { + body: function(name) { return hex_md5(name) == "15b0a220baa16331e8d80e15367677ad"; }, + args: [ "$name" ], + lang: "js" + } + } + }` + ), + { + $expr: { + $function: { + body: 'function(name) { return hex_md5(name) == "15b0a220baa16331e8d80e15367677ad"; }', + args: ['$name'], + lang: 'js', + }, + }, + } + ); + + assert.deepEqual( + convert('{$match: function() { return this.x === 2; }}'), + { + $match: 'function() { return this.x === 2; }', + } + ); + }); + + context('for Date() and ISODate() without argument', function () { + // mock a specific timestamp with sinon.useFakeTimers + const now = 1533789516225; + const nowStr = '2018-08-09T04:38:36.225Z'; + let clock: sinon.SinonFakeTimers; + + beforeEach(function () { + clock = sinon.useFakeTimers(now); + }); + + afterEach(function () { + clock.restore(); + }); + + it('should support new Date', function () { + assert.deepEqual(convert('new Date()'), { + $date: nowStr, + }); + }); + + it('should support ISODate', function () { + assert.deepEqual(convert('ISODate()'), { + $date: nowStr, + }); + }); + + it('should support new ISODate', function () { + assert.deepEqual(convert('new ISODate()'), { + $date: nowStr, + }); + }); + }); + + it('should support Timestamp', function () { + assert.deepEqual(convert('{t: Timestamp(0, 0)}'), { + t: { $timestamp: { i: 0, t: 0 } }, + }); + }); + + it('should support new Timestamp', function () { + assert.deepEqual(convert('{t: new Timestamp(0, 0)}'), { + t: { $timestamp: { i: 0, t: 0 } }, + }); + }); + + it('should support inline regex', function () { + assert.deepEqual(convert('/some.*regex+/i'), { + $regex: 'some.*regex+', + $options: 'i', + }); + }); + + it('should support RegExp', function () { + assert.deepEqual(convert("RegExp('some.*regex+', 'i')"), { + $regex: 'some.*regex+', + $options: 'i', + }); + }); + + it('should support new RegExp', function () { + assert.deepEqual(convert("new RegExp('some.*regex+', 'i')"), { + $regex: 'some.*regex+', + $options: 'i', + }); + }); + + it('should support ObjectId', function () { + assert.deepEqual(convert('ObjectId("58c33a794d08b991e3648fd2")'), { + $oid: '58c33a794d08b991e3648fd2', + }); + }); + + it('should support new ObjectId', function () { + assert.deepEqual(convert('new ObjectId("58c33a794d08b991e3648fd2")'), { + $oid: '58c33a794d08b991e3648fd2', + }); + }); + + it('should support ObjectID', function () { + assert.deepEqual(convert('ObjectID("58c33a794d08b991e3648fd2")'), { + $oid: '58c33a794d08b991e3648fd2', + }); + }); + + it('should support new ObjectID', function () { + assert.deepEqual(convert('new ObjectID("58c33a794d08b991e3648fd2")'), { + $oid: '58c33a794d08b991e3648fd2', + }); + }); + + it('should support NumberLong', function () { + assert.deepEqual(convert('NumberLong("1234567890")'), { + $numberLong: '1234567890', + }); + }); + + it('should support NumberLong > MAX_SAFE_INTEGER', function () { + assert.deepEqual(convert('NumberLong("345678654321234552")'), { + $numberLong: '345678654321234552', + }); + }); + + it('should support new NumberLong', function () { + assert.deepEqual(convert('new NumberLong("1234567890")'), { + $numberLong: '1234567890', + }); + }); + + it('should support NumberInt', function () { + assert.deepEqual(convert('NumberInt("1234567890")'), { + $numberInt: '1234567890', + }); + }); + + it('should support NumberInt with number', function () { + assert.deepEqual(convert('NumberInt(1234567890)'), { + $numberInt: '1234567890', + }); + }); + + it('should support NumberDecimal', function () { + assert.deepEqual(convert('NumberDecimal("10.99")'), { + $numberDecimal: '10.99', + }); + }); + + it('should support new NumberDecimal', function () { + assert.deepEqual(convert('new NumberDecimal("10.99")'), { + $numberDecimal: '10.99', + }); + }); + + it('should support MixKey', function () { + assert.deepEqual(convert('MinKey()'), { $minKey: 1 }); + }); + + it('should support MaxKey', function () { + assert.deepEqual(convert('MaxKey()'), { $maxKey: 1 }); + }); + }); + }); + + describe('isFilterValid', function () { + context('when the string contains a NumberLong', function () { + const query = '{value: NumberLong(1)}'; + const parsed = isFilterValid(query); + it('returns the bson long value', function () { + assert.equal(parsed.value.toNumber(), 1); + }); + }); + + context('when turning off validation', function () { + context('when the query is a valid object', function () { + const query = '{value: NumberLong(1)}'; + const parsed = isFilterValid(query); + + it('returns truthy', function () { + assert.equal(parsed.value.toNumber(), 1); + }); + }); + + context('when the query is not a valid object', function () { + const query = '{value: NumberLong(1)'; + const parsed = isFilterValid(query); + + it('returns false', function () { + assert.equal(parsed, false); + }); + }); + }); + }); + + describe('stringify', function () { + it('should work', function () { + const res = parseFilter('{_id: ObjectId("58c33a794d08b991e3648fd2")}'); + const stringified = stringify(res); + assert.equal(stringified, "{_id: ObjectId('58c33a794d08b991e3648fd2')}"); + }); + it('should not added extra space when nesting', function () { + assert.equal(stringify({ a: { $exists: true } }), '{a: {$exists: true}}'); + }); + + context('when providing a long', function () { + it('correctly converts to NumberLong', function () { + const stringified = stringify({ test: bson.Long.fromNumber(5) }); + assert.equal(stringified, '{test: NumberLong(5)}'); + }); + }); + + context('when providing a decimal128', function () { + it('correctly converts to NumberDecimal', function () { + const stringified = stringify({ + test: bson.Decimal128.fromString('5.5'), + }); + assert.equal(stringified, "{test: NumberDecimal('5.5')}"); + }); + }); + + context('when providing an int32', function () { + it('correctly converts to Int32', function () { + const stringified = stringify({ + test: new bson.Int32(123), + }); + assert.equal(stringified, "{test: NumberInt('123')}"); + }); + }); + + context('when providing a Double', function () { + it('correctly converts to Double', function () { + const stringified = stringify({ + test: new bson.Double(0.8), + }); + assert.equal(stringified, "{test: Double('0.8')}"); + }); + }); + + context('when providing a geo query', function () { + const query = { + coordinates: { + $geoWithin: { + $centerSphere: [[-79, 28], 0.04], + }, + }, + }; + + it('correctly replaces nested tabs with single spaces', function () { + const stringified = stringify(query); + assert.equal( + stringified, + '{coordinates: {$geoWithin: { $centerSphere: [ [ -79, 28 ], 0.04 ]}}}' + ); + }); + }); + + context('when providing a Date', function () { + it('correctly converts to an ISODate', function () { + const res = parseFilter("{test: new Date('2017-01-01T12:35:31.000Z')}"); + const stringified = stringify(res); + assert.equal( + stringified, + "{test: ISODate('2017-01-01T12:35:31.000Z')}" + ); + }); + + it('fallbacks to an invalid ISODate if the provided Date is invalid', function () { + const res = parseFilter("{test: new Date('invalid')}"); + const stringified = stringify(res); + assert.equal(stringified, "{test: ISODate('Invalid Date')}"); + }); + }); + + context('when providing an ISODate', function () { + it('correctly converts to an ISODate', function () { + const res = parseFilter("{test: ISODate('2017-01-01T12:35:31.000Z')}"); + const stringified = stringify(res); + assert.equal( + stringified, + "{test: ISODate('2017-01-01T12:35:31.000Z')}" + ); + }); + + it('fallbacks to an invalid ISODate if the provided ISODate is invalid', function () { + const res = parseFilter("{test: ISODate('invalid')}"); + const stringified = stringify(res); + assert.equal(stringified, "{test: ISODate('Invalid Date')}"); + }); + }); + + context('when providing a DBRef with (collection, oid)', function () { + it('correctly converts to a DBRef', function () { + const res = parseFilter("{dbref: DBRef('col', 1)}"); + const stringified = stringify(res); + assert.equal(stringified, "{dbref: DBRef('col', '1')}"); + }); + }); + + context('when providing a DBRef with (db.collection, oid)', function () { + it('correctly converts to a DBRef', function () { + const res = parseFilter("{dbref: DBRef('db.col', 1)}"); + const stringified = stringify(res); + assert.equal(stringified, "{dbref: DBRef('col', '1', 'db')}"); + }); + }); + + context('when providing a DBRef with (collection, oid, db)', function () { + it('correctly converts to a DBRef', function () { + const res = parseFilter("{dbref: DBRef('col', 1, 'db')}"); + const stringified = stringify(res); + assert.equal(stringified, "{dbref: DBRef('col', '1', 'db')}"); + }); + }); + + context('when provided a RegExp', function () { + it('correctly formats the options', function () { + const res = parseFilter('{name: /foo/i}'); + const stringified = stringify(res); + assert.equal(stringified, '{name: RegExp("foo", \'i\')}'); + }); + + it('escapes quotes', function () { + const res = parseFilter("{name: /'/}"); + const stringified = stringify(res); + assert.equal(stringified, '{name: RegExp("\'")}'); + }); + }); + + context('when provided a Binary', function () { + it('should support BinData', function () { + const res = parseFilter( + `{name: new BinData(${bson.Binary.SUBTYPE_BYTE_ARRAY}, "OyQRAeK7QlWMr0E2xWapYg==")}` + ); + const stringified = stringify(res); + assert.equal( + stringified, + `{name: BinData(${bson.Binary.SUBTYPE_BYTE_ARRAY}, 'OyQRAeK7QlWMr0E2xWapYg==')}` + ); + }); + + it('should support UUID', function () { + const res = parseFilter( + '{name: UUID("3b241101-e2bb-4255-8caf-4136c566a962")}' + ); + const stringified = stringify(res); + assert.equal( + stringified, + "{name: UUID('3b241101-e2bb-4255-8caf-4136c566a962')}" + ); + }); + }); + }); + + describe('project', function () { + it('should default to null', function () { + assert.equal(parseProject(''), null); + assert.equal(parseProject(' '), null); + assert.equal(parseProject('{}'), null); + }); + it('should parse valid project strings', function () { + assert.deepEqual(parseProject('{_id: 1}'), { _id: 1 }); + assert.deepEqual(parseProject('{_id: -1}'), { _id: -1 }); + assert.deepEqual(parseProject('{comments: { $slice: -1 }}'), { + comments: { $slice: -1 }, + }); + }); + it('should allow any project strings', function () { + assert.deepEqual(isProjectValid('{_id: "a"}'), { _id: 'a' }); + assert.deepEqual(isProjectValid('{_id: "1"}'), { _id: '1' }); + }); + it('should reject broken project strings', function () { + assert.equal(isProjectValid('{grabage'), false); + }); + it('should reject non object project values', function () { + assert.equal(isProjectValid('true'), false); + assert.equal(isProjectValid('123'), false); + assert.equal(isProjectValid('"something"'), false); + assert.equal(isProjectValid('null'), false); + }); + }); + + describe('collation', function () { + it('should default to null', function () { + assert.equal(parseCollation(''), null); + assert.equal(parseCollation(' '), null); + assert.equal(parseCollation('{}'), null); + }); + it('should parse valid collation strings', function () { + assert.deepEqual(parseCollation('{locale: "simple"}'), { + locale: 'simple', + }); + assert.deepEqual(parseCollation('{locale: "en_US", strength: 1}'), { + locale: 'en_US', + strength: 1, + }); + }); + it('should detect invalid collation strings', function () { + assert.equal(isCollationValid('{invalid: "simple"}'), false); + assert.equal(isCollationValid('{locale: ""}'), false); + assert.equal(isCollationValid('{locale: "invalid"}'), false); + }); + }); + + describe('sort', function () { + it('should default to null', function () { + assert.equal(parseSort(''), null); + assert.equal(parseSort(' '), null); + assert.equal(parseSort('{}'), null); + }); + it('should work', function () { + assert.deepEqual(parseSort('{_id: 1}'), { _id: 1 }); + assert.deepEqual(parseSort('{_id: -1}'), { _id: -1 }); + }); + it('should allow objects and arrays as values', function () { + assert.deepEqual(isSortValid(''), null); + assert.deepEqual(isSortValid('{_id: 1}'), { _id: 1 }); + assert.deepEqual(isSortValid('{_id: -1}'), { _id: -1 }); + assert.deepEqual(isSortValid('{_id: "asc"}'), { _id: 'asc' }); + assert.deepEqual(isSortValid('{_id: "desc"}'), { _id: 'desc' }); + assert.deepEqual(isSortValid('{ score: { $meta: "textScore" } }'), { + score: { $meta: 'textScore' }, + }); + assert.deepEqual(isSortValid('[["123", -1]]'), [['123', -1]]); + assert.deepEqual(isSortValid('[["bar", 1]]'), [['bar', 1]]); + }); + it('should reject unsupported sort values', function () { + assert.equal(isSortValid('{_id: "a"}'), false); + assert.equal(isSortValid('{_id: "1"}'), false); + assert.equal(isSortValid('{grabage'), false); + assert.equal(isSortValid('[1]'), false); + assert.equal(isSortValid('["foo"]'), false); + assert.equal(isSortValid('[["foo", "bar"]]'), false); + assert.equal(isSortValid('[[123, -1]]'), false); + }); + it('should handle empty, null, and undefined', function () { + assert.equal(isSortValid(''), null); + assert.equal(isSortValid('null'), null); + assert.equal(isSortValid('undefined'), null); + }); + }); + + describe('skip', function () { + it('should work', function () { + assert.equal(isSkipValid('{skip: "a"}'), false); + assert.equal(isSkipValid('0'), 0); + assert.equal(isSkipValid(1), 1); + assert.equal(isSkipValid(' '), DEFAULT_SKIP); + }); + }); + + describe('limit', function () { + it('should work', function () { + assert.equal(isLimitValid('{limit: "a"}'), false); + assert.equal(isLimitValid('0'), 0); + assert.equal(isLimitValid(1), 1); + assert.equal(isLimitValid(' '), DEFAULT_LIMIT); + }); + }); + + describe('maxTimeMS', function () { + it('Validates as a number', function () { + assert.equal(isMaxTimeMSValid('{maxTimeMS: "a"}'), false); + assert.equal(isMaxTimeMSValid('0'), 0); + assert.equal(isMaxTimeMSValid(1), 1); + assert.equal(isMaxTimeMSValid(' '), DEFAULT_MAX_TIME_MS); + }); + }); + + describe('validate', function () { + it('calls the other validation functions', function () { + assert.deepEqual(isSortValid(''), null); + assert.deepEqual(validate('sort', ''), null); + assert.deepEqual(validate('Sort', ''), null); + assert.deepEqual(validate('sort', '[["123", -1]]'), [['123', -1]]); + assert.deepEqual(validate('limit', ' '), DEFAULT_LIMIT); + }); + }); +}); diff --git a/packages/query-parser/src/index.ts b/packages/query-parser/src/index.ts new file mode 100644 index 00000000..47b319d1 --- /dev/null +++ b/packages/query-parser/src/index.ts @@ -0,0 +1,339 @@ +import parseShellStringToEJSON, { ParseMode } from 'ejson-shell-parser'; + +import _ from 'lodash'; +import _debug from 'debug'; + +import { COLLATION_OPTIONS } from './constants'; +import { stringify, toJSString } from './stringify'; + +const debug = _debug('mongodb-query-parser'); + +/** @public */ +const DEFAULT_FILTER = {}; +/** @public */ +const DEFAULT_SORT = null; +/** @public */ +const DEFAULT_LIMIT = 0; +/** @public */ +const DEFAULT_SKIP = 0; +/** @public */ +const DEFAULT_PROJECT = null; +/** @public */ +const DEFAULT_COLLATION = null; +/** @public */ +const DEFAULT_MAX_TIME_MS = 60000; // 1 minute in ms +/** @public */ +const QUERY_PROPERTIES = ['filter', 'project', 'sort', 'skip', 'limit']; + +function isEmpty(input: string | number | null | undefined): boolean { + if (input === null || input === undefined) { + return true; + } + const s = _.trim(typeof input === 'number' ? `${input}` : input); + + if (s === '{}') { + return true; + } + return _.isEmpty(s); +} + +function isNumberValid(input: string | number) { + if (isEmpty(input)) { + return 0; + } + return /^\d+$/.test(`${input}`) ? parseInt(`${input}`, 10) : false; +} + +function _parseProject(input: string) { + return parseShellStringToEJSON(input, { mode: ParseMode.Loose }); +} + +function _parseCollation(input: string) { + return parseShellStringToEJSON(input, { mode: ParseMode.Loose }); +} + +/** @public */ +export function parseSort(input: string) { + if (isEmpty(input)) { + return DEFAULT_SORT; + } + return parseShellStringToEJSON(input, { mode: ParseMode.Loose }); +} + +function _parseFilter(input: string) { + return parseShellStringToEJSON(input, { mode: ParseMode.Loose }); +} + +/** @public */ +export function parseFilter(input: string) { + if (isEmpty(input)) { + return DEFAULT_FILTER; + } + return _parseFilter(input); +} + +/** @public */ +export function parseCollation(input: string) { + if (isEmpty(input)) { + return DEFAULT_COLLATION; + } + return _parseCollation(input); +} + +/** + * Validation function for a query `filter`. Must be a valid MongoDB query + * according to the query language. + * @public + * + * @return {Boolean|Object} false if not valid, or the parsed filter. + */ +export function isFilterValid(input: string) { + if (isEmpty(input)) { + return DEFAULT_FILTER; + } + try { + return _parseFilter(input); + } catch (e) { + debug('Filter "%s" is invalid', input, e); + return false; + } +} + +/** + * Validation of collation object keys and values. + * @public + * + * @param {Object} collation + * @return {Boolean|Object} false if not valid, otherwise the parsed project. + */ +function _isCollationValid(collation: any) { + for (const [key, value] of Object.entries(collation)) { + if (!COLLATION_OPTIONS[key]) { + debug('Collation "%s" is invalid bc of its keys', collation); + return false; + } + if ( + COLLATION_OPTIONS[key as keyof typeof COLLATION_OPTIONS].includes( + value as string | number | boolean + ) === false + ) { + debug('Collation "%s" is invalid bc of its values', collation); + return false; + } + } + return collation; +} + +/** + * Validation function for a query `collation`. + * @public + * + * @return {Boolean|Object} false if not valid, or the parsed filter. + */ +export function isCollationValid(input: string) { + if (isEmpty(input)) { + return DEFAULT_COLLATION; + } + try { + const parsed = _parseCollation(input); + return _isCollationValid(parsed); + } catch (e) { + debug('Collation "%s" is invalid', input, e); + return false; + } +} + +function isValueOkForProject() { + /** + * Since server 4.4, project in find queries supports everything that + * aggregations $project supports (which is basically anything at all) so we + * effectively allow everything as a project value and keep this method for + * the context + * + * @see {@link https://docs.mongodb.com/manual/release-notes/4.4/#projection} + */ + return true; +} + +/** @public */ +export function parseProject(input: string) { + if (isEmpty(input)) { + return DEFAULT_PROJECT; + } + return _parseProject(input); +} + +/** + * Validation function for a query `project`. Must only have 0 or 1 as values. + * @public + * + * @return {Boolean|Object} false if not valid, otherwise the parsed project. + */ +export function isProjectValid(input: string) { + if (isEmpty(input)) { + return DEFAULT_PROJECT; + } + + try { + const parsed = _parseProject(input); + + if (!_.isObject(parsed)) { + debug('Project "%s" is invalid. Only documents are allowed', input); + return false; + } + + if (!_.every(parsed, isValueOkForProject)) { + debug('Project "%s" is invalid bc of its values', input); + return false; + } + + return parsed; + } catch (e) { + debug('Project "%s" is invalid', input, e); + return false; + } +} + +const ALLOWED_SORT_VALUES = [1, -1, 'asc', 'desc']; + +function isValueOkForSortDocument(val: any): boolean { + return ( + _.includes(ALLOWED_SORT_VALUES, val) || + !!(_.isObject(val) && (val as { $meta: string }).$meta) + ); +} + +function isValueOkForSortArray(val: any): boolean { + return ( + _.isArray(val) && + val.length === 2 && + _.isString(val[0]) && + isValueOkForSortDocument(val[1]) + ); +} + +/** + * Validation function for a query `sort`. Must only have -1 or 1 as values. + * @public + * + * @return {Boolean|Object} false if not valid, otherwise the cleaned-up sort. + */ +export function isSortValid(input: string) { + try { + const parsed = parseSort(input); + + if (isEmpty(parsed)) { + return DEFAULT_SORT; + } + + if (_.isArray(parsed) && _.every(parsed, isValueOkForSortArray)) { + return parsed; + } + + if ( + _.isObject(parsed) && + !_.isArray(parsed) && + _.every(parsed, isValueOkForSortDocument) + ) { + return parsed; + } + + debug('Sort "%s" is invalid bc of its values', input); + return false; + } catch (e) { + debug('Sort "%s" is invalid', input, e); + return false; + } +} + +/** + * Validation function for a query `maxTimeMS`. Must be digits only. + * @public + * + * Returns false if not valid, otherwise the cleaned-up max time ms. + */ +export function isMaxTimeMSValid(input: string | number): number | false { + if (isEmpty(input)) { + return DEFAULT_MAX_TIME_MS; + } + return isNumberValid(input); +} + +/** + * Validation function for a query `skip`. Must be digits only. + * @public + * + * Returns false if not valid, otherwise the cleaned-up skip. + */ +export function isSkipValid(input: string | number): number | false { + if (isEmpty(input)) { + return DEFAULT_SKIP; + } + return isNumberValid(input); +} + +/** + * Validation function for a query `limit`. Must be digits only. + * @public + * + * Returns false if not valid, otherwise the cleaned-up limit. + */ +export function isLimitValid(input: string | number): number | false { + if (isEmpty(input)) { + return DEFAULT_LIMIT; + } + return isNumberValid(input); +} + +const validatorFunctions = { + isMaxTimeMSValid, + isFilterValid, + isProjectValid, + isSortValid, + isLimitValid, + isSkipValid, + isCollationValid, + isNumberValid, +}; + +/** @public */ +export function validate(what: string, input: string) { + const validator = + validatorFunctions[ + `is${_.upperFirst(what)}Valid` as keyof typeof validatorFunctions + ]; + if (!validator) { + debug('Do not know how to validate `%s`. Returning false.', what); + return false; + } + return validator(input); +} + +/** @public */ +export default function queryParser( + filter: string, + project: string | null = DEFAULT_PROJECT +) { + if (arguments.length === 1) { + if (_.isString(filter)) { + return _parseFilter(filter); + } + } + return { + filter: _parseFilter(filter), + project: project !== DEFAULT_PROJECT ? _parseProject(project) : project, + }; +} + +export { + stringify, + toJSString, + QUERY_PROPERTIES, + DEFAULT_FILTER, + DEFAULT_SORT, + DEFAULT_LIMIT, + DEFAULT_SKIP, + DEFAULT_PROJECT, + DEFAULT_COLLATION, + DEFAULT_MAX_TIME_MS, +}; diff --git a/packages/query-parser/src/stringify.ts b/packages/query-parser/src/stringify.ts new file mode 100644 index 00000000..7d5bb4cb --- /dev/null +++ b/packages/query-parser/src/stringify.ts @@ -0,0 +1,163 @@ +/** + * TODO: lucas: this is now used in several modules (import-export, query-parser, probably others). Refactor into 1 shared place. bson? + */ +import type { + Binary, + BSONValue, + Code, + DBRef, + Decimal128, + Double, + Int32, + Long, + ObjectId, + Timestamp, +} from 'bson'; +import { stringify as toJavascriptString } from 'javascript-stringify'; + +/** + * [`Object.prototype.toString.call(value)`, `string type name`] + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString#Using_toString_to_detect_object_class + */ +const TYPE_FOR_TO_STRING = new Map([ + ['[object Array]', 'Array'], + ['[object Object]', 'Object'], + ['[object String]', 'String'], + ['[object Date]', 'Date'], + ['[object Number]', 'Number'], + ['[object Function]', 'Function'], + ['[object RegExp]', 'RegExp'], + ['[object Boolean]', 'Boolean'], + ['[object Null]', 'Null'], + ['[object Undefined]', 'Undefined'], +]); + +function detectType(value: BSONValue) { + return TYPE_FOR_TO_STRING.get(Object.prototype.toString.call(value)); +} + +function getTypeDescriptorForValue(value: BSONValue) { + const t = detectType(value); + const _bsontype = t === 'Object' && value._bsontype; + return { + type: _bsontype || t, + isBSON: !!_bsontype, + }; +} + +const BSON_TO_JS_STRING = { + Code: function (v: Code) { + if (v.scope) { + return `Code('${v.code}',${JSON.stringify(v.scope)})`; + } + return `Code('${v.code}')`; + }, + ObjectID: function (v: ObjectId) { + return `ObjectId('${v.toString('hex')}')`; + }, + ObjectId: function (v: ObjectId) { + return `ObjectId('${v.toString('hex')}')`; + }, + Binary: function (v: Binary) { + const subType = v.sub_type; + if (subType === 4 && v.buffer.length === 16) { + let uuidHex = ''; + try { + // Try to get the pretty hex version of the UUID + uuidHex = v.toUUID().toString(); + } catch { + // If uuid is not following the uuid format converting it to UUID will + // fail, we don't want the UI to fail rendering it and instead will + // just display "unformatted" hex value of the binary whatever it is + uuidHex = v.toString('hex'); + } + return `UUID('${uuidHex}')`; + } + // The `Binary.buffer.toString` type says it doesn't accept + // arguments. However it does, and a test will fail without it. + return `BinData(${subType.toString(16)}, '${v.toString('base64')}')`; + }, + DBRef: function (v: DBRef) { + if (v.db) { + return `DBRef('${v.collection}', '${v.oid.toString()}', '${v.db}')`; + } + + return `DBRef('${v.collection}', '${v.oid.toString()}')`; + }, + Timestamp: function (v: Timestamp) { + return `Timestamp({ t: ${v.high}, i: ${v.low} })`; + }, + Long: function (v: Long) { + return `NumberLong(${v.toString()})`; + }, + Decimal128: function (v: Decimal128) { + return `NumberDecimal('${v.toString()}')`; + }, + Double: function (v: Double) { + return `Double('${v.toString()}')`; + }, + Int32: function (v: Int32) { + return `NumberInt('${v.toString()}')`; + }, + MaxKey: function () { + return 'MaxKey()'; + }, + MinKey: function () { + return 'MinKey()'; + }, + Date: function (v: Date) { + return BSON_TO_JS_STRING.ISODate(v); + }, + ISODate: function (v: Date) { + try { + return `ISODate('${v.toISOString()}')`; + } catch (ex) { + return `ISODate('${v.toString()}')`; + } + }, + RegExp: function (v: RegExp) { + let o = ''; + let hasOptions = false; + + if (v.global) { + hasOptions = true; + o += 'g'; + } + if (v.ignoreCase) { + hasOptions = true; + o += 'i'; + } + if (v.multiline) { + hasOptions = true; + o += 'm'; + } + + return `RegExp(${JSON.stringify(v.source)}${hasOptions ? `, '${o}'` : ''})`; + }, +}; + +/** @public */ +export function toJSString( + obj: unknown, + ind?: Parameters[2] +): string | undefined { + return toJavascriptString( + obj, + function (value, indent, stringify) { + const t = getTypeDescriptorForValue(value); + const toJs = BSON_TO_JS_STRING[t.type as keyof typeof BSON_TO_JS_STRING]; + if (!toJs) { + return stringify(value); + } + return toJs(value); + }, + ind || ' ' + ); +} + +/** @public */ +export function stringify(obj: unknown): string | undefined { + return toJSString(obj) + ?.replace(/ ?\n ? ?/g, '') + .replace(/ {2,}/g, ' '); +} diff --git a/packages/query-parser/tsconfig-lint.json b/packages/query-parser/tsconfig-lint.json new file mode 100644 index 00000000..6bdef84f --- /dev/null +++ b/packages/query-parser/tsconfig-lint.json @@ -0,0 +1,5 @@ +{ + "extends": "./tsconfig.json", + "include": ["**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/query-parser/tsconfig.json b/packages/query-parser/tsconfig.json new file mode 100644 index 00000000..21899b27 --- /dev/null +++ b/packages/query-parser/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@mongodb-js/tsconfig-devtools/tsconfig.common.json", + "compilerOptions": { + "outDir": "dist", + "allowJs": true + }, + "include": ["src/**/*"], + "exclude": ["./src/**/*.spec.*"] +}