commit 06fbe82dceb9d4a57b4ef67209536a097ed32582 Author: Marek Piasecki Date: Wed Jan 11 16:09:30 2023 +0100 npx imba create (Vite) diff --git a/index.html b/index.html new file mode 100644 index 0000000..52c9bb2 --- /dev/null +++ b/index.html @@ -0,0 +1,11 @@ + + + + + + Imba Vite Template + + + + + diff --git a/node_modules/.bin/acorn b/node_modules/.bin/acorn new file mode 120000 index 0000000..cf76760 --- /dev/null +++ b/node_modules/.bin/acorn @@ -0,0 +1 @@ +../acorn/bin/acorn \ No newline at end of file diff --git a/node_modules/.bin/cross-env b/node_modules/.bin/cross-env new file mode 120000 index 0000000..7c86606 --- /dev/null +++ b/node_modules/.bin/cross-env @@ -0,0 +1 @@ +../cross-env/src/bin/cross-env.js \ No newline at end of file diff --git a/node_modules/.bin/cross-env-shell b/node_modules/.bin/cross-env-shell new file mode 120000 index 0000000..a9149d1 --- /dev/null +++ b/node_modules/.bin/cross-env-shell @@ -0,0 +1 @@ +../cross-env/src/bin/cross-env-shell.js \ No newline at end of file diff --git a/node_modules/.bin/esbuild b/node_modules/.bin/esbuild new file mode 120000 index 0000000..c83ac07 --- /dev/null +++ b/node_modules/.bin/esbuild @@ -0,0 +1 @@ +../esbuild/bin/esbuild \ No newline at end of file diff --git a/node_modules/.bin/imba b/node_modules/.bin/imba new file mode 120000 index 0000000..ab99b6d --- /dev/null +++ b/node_modules/.bin/imba @@ -0,0 +1 @@ +../imba/bin/imba \ No newline at end of file diff --git a/node_modules/.bin/imbac b/node_modules/.bin/imbac new file mode 120000 index 0000000..3fb8b7e --- /dev/null +++ b/node_modules/.bin/imbac @@ -0,0 +1 @@ +../imba/bin/imbac \ No newline at end of file diff --git a/node_modules/.bin/lz-string b/node_modules/.bin/lz-string new file mode 120000 index 0000000..14bd70d --- /dev/null +++ b/node_modules/.bin/lz-string @@ -0,0 +1 @@ +../lz-string/bin/bin.js \ No newline at end of file diff --git a/node_modules/.bin/nanoid b/node_modules/.bin/nanoid new file mode 120000 index 0000000..e2be547 --- /dev/null +++ b/node_modules/.bin/nanoid @@ -0,0 +1 @@ +../nanoid/bin/nanoid.cjs \ No newline at end of file diff --git a/node_modules/.bin/node-which b/node_modules/.bin/node-which new file mode 120000 index 0000000..6f8415e --- /dev/null +++ b/node_modules/.bin/node-which @@ -0,0 +1 @@ +../which/bin/node-which \ No newline at end of file diff --git a/node_modules/.bin/resolve b/node_modules/.bin/resolve new file mode 120000 index 0000000..b6afda6 --- /dev/null +++ b/node_modules/.bin/resolve @@ -0,0 +1 @@ +../resolve/bin/resolve \ No newline at end of file diff --git a/node_modules/.bin/rollup b/node_modules/.bin/rollup new file mode 120000 index 0000000..5939621 --- /dev/null +++ b/node_modules/.bin/rollup @@ -0,0 +1 @@ +../rollup/dist/bin/rollup \ No newline at end of file diff --git a/node_modules/.bin/vite b/node_modules/.bin/vite new file mode 120000 index 0000000..6d1e3be --- /dev/null +++ b/node_modules/.bin/vite @@ -0,0 +1 @@ +../vite/bin/vite.js \ No newline at end of file diff --git a/node_modules/.bin/vite-node b/node_modules/.bin/vite-node new file mode 120000 index 0000000..d68f74c --- /dev/null +++ b/node_modules/.bin/vite-node @@ -0,0 +1 @@ +../vite-node/vite-node.mjs \ No newline at end of file diff --git a/node_modules/.bin/vitest b/node_modules/.bin/vitest new file mode 120000 index 0000000..2273497 --- /dev/null +++ b/node_modules/.bin/vitest @@ -0,0 +1 @@ +../vitest/vitest.mjs \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..cdae4c7 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,2712 @@ +{ + "name": "slots", + "version": "0.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@adobe/css-tools": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.0.1.tgz", + "integrity": "sha512-+u76oB43nOHrF4DDWRLWDCtci7f3QJoEBigemIdIeTi1ODqjx6Tad9NCVnPRwewWlKkVab5PlK8DCtPTyX7S8g==", + "dev": true, + "peer": true + }, + "node_modules/@antfu/install-pkg": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-0.1.1.tgz", + "integrity": "sha512-LyB/8+bSfa0DFGC06zpCEfs89/XoWZwws5ygEa5D+Xsm3OfI+aXQ86VgVG7Acyef+rSZ5HE7J8rrxzrQeM3PjQ==", + "dev": true, + "dependencies": { + "execa": "^5.1.1", + "find-up": "^5.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", + "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/highlight": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.19.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", + "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", + "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.18.6", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "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, + "peer": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "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, + "peer": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "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, + "peer": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "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": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true, + "peer": true + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.8.0" + } + }, + "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": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/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, + "peer": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/runtime": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.20.7.tgz", + "integrity": "sha512-UF0tvkUtxwAgZ5W/KrkHf0Rn0fdnLDU9ScxBrEVNUprE/MzirjK4MJUX1/BVDv00Sv8cljtukVK1aky++X1SjQ==", + "dev": true, + "peer": true, + "dependencies": { + "regenerator-runtime": "^0.13.11" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.3.1.tgz", + "integrity": "sha512-wlrznINZI5sMjwvUoLVk617ll/UYfGIZNxmbU+Pa7wmkL4vYzhV9R2pwVqUh4NWWuLQWkI8+8mOkxs//prKQ3g==", + "dev": true, + "peer": true, + "dependencies": { + "jest-get-type": "^29.2.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/schemas": { + "version": "29.0.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.0.0.tgz", + "integrity": "sha512-3Ab5HgYIIAnS0HjqJHQYZS+zXc4tUmTmBH3z83ajI6afXp8X3ZtdLX+nXx+I7LNkJD7uN9LAVhgnjDgZa2z0kA==", + "dev": true, + "peer": true, + "dependencies": { + "@sinclair/typebox": "^0.24.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/types": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.3.1.tgz", + "integrity": "sha512-d0S0jmmTpjnhCmNpApgX3jrUZgZ22ivKJRvL2lli5hpCRoNnp1f85r2/wpKfXuYu8E7Jjh1hGfhPyup1NM5AmA==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/schemas": "^29.0.0", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@rollup/pluginutils": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.1.tgz", + "integrity": "sha512-iKnFXr7NkdZAIHiIWE+BX5ULi/ucVFYWD6TbAV+rZctiRTY2PL6tsIKhoIOaoskiWAkgu+VsbXgUVDNLHf+InQ==", + "dev": true, + "dependencies": { + "estree-walker": "^2.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.24.51", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.24.51.tgz", + "integrity": "sha512-1P1OROm/rdubP5aFDSZQILU0vrLCJ4fvHt6EoqHEM+2D/G5MK3bIaymUKLit8Js9gbns5UyJnkP/TZROLw4tUA==", + "dev": true, + "peer": true + }, + "node_modules/@testing-library/dom": { + "version": "8.19.1", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-8.19.1.tgz", + "integrity": "sha512-P6iIPyYQ+qH8CvGauAqanhVnjrnRe0IZFSYCeGkSRW9q3u8bdVn2NPI+lasFyVsEQn1J/IFmp5Aax41+dAP9wg==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "^5.0.0", + "chalk": "^4.1.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.4.4", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@testing-library/jest-dom": { + "version": "5.16.5", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-5.16.5.tgz", + "integrity": "sha512-N5ixQ2qKpi5OLYfwQmUb/5mSV9LneAcaUfp32pn4yCnpb8r/Yz0pXFPck21dIicKmi+ta5WRAknkZCfA8refMA==", + "dev": true, + "peer": true, + "dependencies": { + "@adobe/css-tools": "^4.0.1", + "@babel/runtime": "^7.9.2", + "@types/testing-library__jest-dom": "^5.9.1", + "aria-query": "^5.0.0", + "chalk": "^3.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.5.6", + "lodash": "^4.17.15", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=8", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/@testing-library/jest-dom/node_modules/chalk": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", + "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "dev": true, + "peer": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.1.tgz", + "integrity": "sha512-XTIieEY+gvJ39ChLcB4If5zHtPxt3Syj5rgZR+e1ctpmK8NjPf0zFqsz4JpLJT0xla9GFDKjy8Cpu331nrmE1Q==", + "dev": true, + "peer": true + }, + "node_modules/@types/chai": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.4.tgz", + "integrity": "sha512-KnRanxnpfpjUTqTCXslZSEdLfXExwgNxYPdiO2WGUj8+HDjFi8R3k5RVKPeSCzLjCcshCAtVO2QBbVuAV4kTnw==", + "dev": true, + "peer": true + }, + "node_modules/@types/chai-subset": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.3.tgz", + "integrity": "sha512-frBecisrNGz+F4T6bcc+NLeolfiojh5FxW2klu669+8BARtyQv2C/GkNW6FUodVe4BroGMP/wER/YDGc7rEllw==", + "dev": true, + "peer": true, + "dependencies": { + "@types/chai": "*" + } + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz", + "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==", + "dev": true, + "peer": true + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", + "dev": true, + "peer": true, + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", + "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", + "dev": true, + "peer": true, + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/jest": { + "version": "29.2.5", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.2.5.tgz", + "integrity": "sha512-H2cSxkKgVmqNHXP7TC2L/WUorrZu8ZigyRywfVzv6EyBlxj39n4C00hjXYQWsbwqgElaj/CiAeSRmk5GoaKTgw==", + "dev": true, + "peer": true, + "dependencies": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + } + }, + "node_modules/@types/jest/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@types/jest/node_modules/pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@types/jest/node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + }, + "node_modules/@types/node": { + "version": "18.11.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz", + "integrity": "sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==", + "dev": true, + "peer": true + }, + "node_modules/@types/stack-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", + "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", + "dev": true, + "peer": true + }, + "node_modules/@types/testing-library__jest-dom": { + "version": "5.14.5", + "resolved": "https://registry.npmjs.org/@types/testing-library__jest-dom/-/testing-library__jest-dom-5.14.5.tgz", + "integrity": "sha512-SBwbxYoyPIvxHbeHxTZX2Pe/74F/tX2/D3mMvzabdeJ25bBojfW0TyB8BHrbq/9zaaKICJZjLP+8r6AeZMFCuQ==", + "dev": true, + "peer": true, + "dependencies": { + "@types/jest": "*" + } + }, + "node_modules/@types/yargs": { + "version": "17.0.19", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.19.tgz", + "integrity": "sha512-cAx3qamwaYX9R0fzOIZAlFpo4A+1uBVCxqpKz9D26uTF4srRXaGTTsikQmaotCtNdbhzyUH7ft6p9ktz9s6UNQ==", + "dev": true, + "peer": true, + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==", + "dev": true, + "peer": true + }, + "node_modules/acorn": { + "version": "8.8.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.1.tgz", + "integrity": "sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA==", + "dev": true, + "peer": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", + "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "peer": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/aria-query": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.1.3.tgz", + "integrity": "sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==", + "dev": true, + "peer": true, + "dependencies": { + "deep-equal": "^2.0.5" + } + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "peer": true, + "engines": { + "node": "*" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz", + "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "peer": true + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "peer": true, + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chai": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.7.tgz", + "integrity": "sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==", + "dev": true, + "peer": true, + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^4.1.2", + "get-func-name": "^2.0.0", + "loupe": "^2.3.1", + "pathval": "^1.1.1", + "type-detect": "^4.0.5" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "peer": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/check-error": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", + "integrity": "sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==", + "dev": true, + "peer": true, + "engines": { + "node": "*" + } + }, + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "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" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/ci-info": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.7.1.tgz", + "integrity": "sha512-4jYS4MOAaCIStSRwiuxc4B8MYhIe676yO1sYGzARnjXkWpmzZMMYxY6zu8WYWDhSuth5zhrQ1rhNSibyyvv4/w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "peer": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "peer": true + }, + "node_modules/colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "dev": true, + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/cross-env": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", + "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.1" + }, + "bin": { + "cross-env": "src/bin/cross-env.js", + "cross-env-shell": "src/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=10.14", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "peer": true + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "dev": true, + "peer": true, + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/deep-equal": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.0.tgz", + "integrity": "sha512-RdpzE0Hv4lhowpIUKKMJfeH6C1pXdtT1/it80ubgWqwI3qpuxUBpC1S4hnHg+zjnuOoDkzUtUCEEkG+XG5l3Mw==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "es-get-iterator": "^1.1.2", + "get-intrinsic": "^1.1.3", + "is-arguments": "^1.1.1", + "is-array-buffer": "^3.0.1", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "isarray": "^2.0.5", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.4.3", + "side-channel": "^1.0.4", + "which-boxed-primitive": "^1.0.2", + "which-collection": "^1.0.1", + "which-typed-array": "^1.1.9" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/define-properties": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.4.tgz", + "integrity": "sha512-uckOqKcfaVvtBdsVkdPv3XjveQJsNQqmhXgRi8uhvWWuPYZCNlzT8qAyblUgNoXdHdjMTzAqeGjAoli8f+bzPA==", + "dev": true, + "peer": true, + "dependencies": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/diff": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.1.0.tgz", + "integrity": "sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw==", + "dev": true, + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/diff-sequences": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.3.1.tgz", + "integrity": "sha512-hlM3QR272NXCi4pq+N4Kok4kOp6EsgOM3ZSpJI7Da3UAs+Ttsi8MRmB6trM/lhyzUxGfOgnpkHtgqm5Q/CTcfQ==", + "dev": true, + "peer": true, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/dom-accessibility-api": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.15.tgz", + "integrity": "sha512-8o+oVqLQZoruQPYy3uAAQtc6YbtSiRq5aPJBhJ82YTJRHvI6ofhYAkC81WmjFTnfUbqg6T3aCglIpU9p/5e7Cw==", + "dev": true, + "peer": true + }, + "node_modules/dotenv": { + "version": "16.0.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.3.tgz", + "integrity": "sha512-7GO6HghkA5fYG9TYnNxi14/7K9f5occMlp3zXAuSxn7CKCxt9xbNWG7yF8hTCSUchlfWSe3uLmlPfigevRItzQ==", + "dev": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/es-get-iterator": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.2.tgz", + "integrity": "sha512-+DTO8GYwbMCwbywjimwZMHp8AuYXOS2JZFWoi2AlPOS3ebnII9w/NLpNZtA7A0YLaVDw+O7KFCeoIV7OPvM7hQ==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.0", + "has-symbols": "^1.0.1", + "is-arguments": "^1.1.0", + "is-map": "^2.0.2", + "is-set": "^2.0.2", + "is-string": "^1.0.5", + "isarray": "^2.0.5" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/esbuild": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.15.18.tgz", + "integrity": "sha512-x/R72SmW3sSFRm5zrrIjAhCeQSAWoni3CmHEqfQrZIQTM3lVCdehdwuIqaOtfC2slvpdlLa62GYoN8SxT23m6Q==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/android-arm": "0.15.18", + "@esbuild/linux-loong64": "0.15.18", + "esbuild-android-64": "0.15.18", + "esbuild-android-arm64": "0.15.18", + "esbuild-darwin-64": "0.15.18", + "esbuild-darwin-arm64": "0.15.18", + "esbuild-freebsd-64": "0.15.18", + "esbuild-freebsd-arm64": "0.15.18", + "esbuild-linux-32": "0.15.18", + "esbuild-linux-64": "0.15.18", + "esbuild-linux-arm": "0.15.18", + "esbuild-linux-arm64": "0.15.18", + "esbuild-linux-mips64le": "0.15.18", + "esbuild-linux-ppc64le": "0.15.18", + "esbuild-linux-riscv64": "0.15.18", + "esbuild-linux-s390x": "0.15.18", + "esbuild-netbsd-64": "0.15.18", + "esbuild-openbsd-64": "0.15.18", + "esbuild-sunos-64": "0.15.18", + "esbuild-windows-32": "0.15.18", + "esbuild-windows-64": "0.15.18", + "esbuild-windows-arm64": "0.15.18" + } + }, + "node_modules/esbuild-linux-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.15.18.tgz", + "integrity": "sha512-hNSeP97IviD7oxLKFuii5sDPJ+QHeiFTFLoLm7NZQligur8poNOWGIgpQ7Qf8Balb69hptMZzyOBIPtY09GZYw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/expect": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.3.1.tgz", + "integrity": "sha512-gGb1yTgU30Q0O/tQq+z30KBWv24ApkMgFUpvKBkyLUBL68Wv8dHdJxTBZFl/iT8K/bqDHvUYRH6IIN3rToopPA==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/expect-utils": "^29.3.1", + "jest-get-type": "^29.2.0", + "jest-matcher-utils": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/fill-range": { + "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, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "dev": true, + "peer": true, + "dependencies": { + "is-callable": "^1.1.3" + } + }, + "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 + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-func-name": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", + "integrity": "sha512-Hm0ixYtaSZ/V7C8FJrtZIuBBI+iSgL+1Aq82zSu8VQNB4S3Gk8e7Qs3VwBDJAhmRZcFqkl3tQu36g/Foh5I5ig==", + "dev": true, + "peer": true, + "engines": { + "node": "*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.3.tgz", + "integrity": "sha512-QJVz1Tj7MS099PevUG5jvnt9tSkXN8K14dxQlikJuPt4uD9hHAHjLyLBiLR5zELelBdD9QNRAXZzsJx0WaDL9A==", + "dev": true, + "peer": true, + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dev": true, + "peer": true, + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", + "dev": true, + "peer": true + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-bigints": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", + "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", + "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", + "dev": true, + "peer": true, + "dependencies": { + "get-intrinsic": "^1.1.1" + }, + "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==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "dev": true, + "peer": true, + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true, + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/imba": { + "version": "2.0.0-alpha.226", + "resolved": "https://registry.npmjs.org/imba/-/imba-2.0.0-alpha.226.tgz", + "integrity": "sha512-QAg+ztLE8nbIqzT76ggrlqFzxM+c/zYHHcCMyGNx6U02yq8VcD8aMdUJGlDyvvKoRj5hzzdh99t0bdt6LUuCTw==", + "dev": true, + "dependencies": { + "@antfu/install-pkg": "^0.1.1", + "chokidar": "^3.4.3", + "colors": "^1.4.0", + "cross-spawn": "^7.0.3", + "dotenv": "^16.0.3", + "esbuild": "^0.15.2", + "local-pkg": "^0.4.2", + "picocolors": "^1.0.0", + "prompts": "^2.4.2" + }, + "bin": { + "imba": "bin/imba", + "imbac": "bin/imbac" + }, + "engines": { + "node": ">=13.10.0" + }, + "peerDependencies": { + "@testing-library/dom": "*", + "@testing-library/jest-dom": "*", + "vite": "*", + "vite-node": "*", + "vite-plugin-imba": "*", + "vitest": "*" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-arguments": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.1.tgz", + "integrity": "sha512-ASfLknmY8Xa2XtB4wmbz13Wu202baeA18cJBCeCy0wXUHZF0IPyVEXqKEcd+t2fNSLLL1vC6k7lxZEojNbISXQ==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "is-typed-array": "^1.1.10" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", + "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "dev": true, + "peer": true, + "dependencies": { + "has-bigints": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "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==", + "dev": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-boolean-object": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", + "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", + "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "dev": true, + "peer": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-map": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.2.tgz", + "integrity": "sha512-cOZFQQozTha1f4MxLFzlgKYPTyj26picdZTx82hbc/Xf4K/tZOOXSCkMvU4pKioRXGDLJRn0GM7Upe7kR721yg==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", + "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", + "dev": true, + "peer": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regex": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.2.tgz", + "integrity": "sha512-+2cnTEZeY5z/iXGbLhPrOAaK/Mau5k5eXq9j14CpRTftq0pAJu2MwVRSZhyZWBzx3o6X795Lz6Bpb6R0GKf37g==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz", + "integrity": "sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-string": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", + "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "dev": true, + "peer": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", + "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "dev": true, + "peer": true, + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.10", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.10.tgz", + "integrity": "sha512-PJqgEHiWZvMpaFZ3uTc8kHPM4+4ADTlDniuQL7cU/UDA0Ql7F70yGfHph3cLNe+c9toaigv+DFzTJKhc2CtO6A==", + "dev": true, + "peer": true, + "dependencies": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.1.tgz", + "integrity": "sha512-NSBR4kH5oVj1Uwvv970ruUkCV7O1mzgVFO4/rev2cLRda9Tm9HrL70ZPut4rOHgY0FNrUu9BCbXA2sdQ+x0chA==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.2.tgz", + "integrity": "sha512-t2yVvttHkQktwnNNmBQ98AhENLdPUTDTE21uPqAQ0ARwQfGeQKRVS0NNurH7bTf7RrvcVn1OOge45CnBeHCSmg==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "peer": true + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "node_modules/jest-diff": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.3.1.tgz", + "integrity": "sha512-vU8vyiO7568tmin2lA3r2DP8oRvzhvRcD4DjpXc6uGveQodyk7CKLhQlCSiwgx3g0pFaE88/KLZ0yaTWMc4Uiw==", + "dev": true, + "peer": true, + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.3.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-diff/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/jest-diff/node_modules/pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-diff/node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + }, + "node_modules/jest-get-type": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.2.0.tgz", + "integrity": "sha512-uXNJlg8hKFEnDgFsrCjznB+sTxdkuqiCL6zMgA75qEbAJjJYTs9XPrvDctrEig2GDow22T/LvHgO57iJhXB/UA==", + "dev": true, + "peer": true, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.3.1.tgz", + "integrity": "sha512-fkRMZUAScup3txIKfMe3AIZZmPEjWEdsPJFK3AIy5qRohWqQFg1qrmKfYXR9qEkNc7OdAu2N4KPHibEmy4HPeQ==", + "dev": true, + "peer": true, + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.3.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/jest-matcher-utils/node_modules/pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils/node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + }, + "node_modules/jest-message-util": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.3.1.tgz", + "integrity": "sha512-lMJTbgNcDm5z+6KDxWtqOFWlGQxD6XaYwBqHR8kmpkP+WWWG90I35kdtQHY67Ay5CSuydkTBbJG+tH9JShFCyA==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.3.1", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/jest-message-util/node_modules/pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util/node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + }, + "node_modules/jest-util": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.3.1.tgz", + "integrity": "sha512-7YOVZaiX7RJLv76ZfHt4nbNEzzTRiMW/IiOG7ZOKmTXmoGBxUDefgMAxQubu6WPVqP5zSzAdZG0FfLcC7HOIFQ==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "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, + "peer": true + }, + "node_modules/jsonc-parser": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.0.tgz", + "integrity": "sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==", + "dev": true, + "peer": true + }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/local-pkg": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.4.2.tgz", + "integrity": "sha512-mlERgSPrbxU3BP4qBqAvvwlgW4MTg78iwJdGGnv7kibKjWcJksrG3t6LB5lXI93wXRDvG4NpUgJFmTG4T6rdrg==", + "dev": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true, + "peer": true + }, + "node_modules/loupe": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", + "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", + "dev": true, + "peer": true, + "dependencies": { + "get-func-name": "^2.0.0" + } + }, + "node_modules/lz-string": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.4.4.tgz", + "integrity": "sha512-0ckx7ZHRPqb0oUm8zNr+90mtf9DQB60H1wMCjBtfi62Kl3a7JbHob6gA2bC+xRvZoOL+1hzUK8jeuEIQE8svEQ==", + "dev": true, + "peer": true, + "bin": { + "lz-string": "bin/bin.js" + } + }, + "node_modules/magic-string": { + "version": "0.26.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.26.7.tgz", + "integrity": "sha512-hX9XH3ziStPoPhJxLq1syWuZMxbDvGNbVchfrdCtanC7D13888bMFow61x8axrx+GfHLtVeAx2kxL7tTGRl+Ow==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.8" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "peer": true, + "dependencies": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/mlly": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.1.0.tgz", + "integrity": "sha512-cwzBrBfwGC1gYJyfcy8TcZU1f+dbH/T+TuOhtYP2wLv/Fb51/uV7HJQfBPtEupZ2ORLRU1EKFS/QfS3eo9+kBQ==", + "dev": true, + "peer": true, + "dependencies": { + "acorn": "^8.8.1", + "pathe": "^1.0.0", + "pkg-types": "^1.0.1", + "ufo": "^1.0.1" + } + }, + "node_modules/mlly/node_modules/pathe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.0.0.tgz", + "integrity": "sha512-nPdMG0Pd09HuSsr7QOKUXO2Jr9eqaDiZvDwdyIhNG5SHYujkQHYKDfGQkulBxvbDHz8oHLsTgKN86LSwYzSHAg==", + "dev": true, + "peer": true + }, + "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 + }, + "node_modules/nanoid": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", + "integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==", + "dev": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/object-inspect": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.2.tgz", + "integrity": "sha512-z+cPxW0QGUp0mcqcsgQyLVRDoXFQbXOwBaqyF7VIgI4TWNQsDHrBpUQslRmIfAoYWdYzs6UlKJtB2XJpTaNSpQ==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-is": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", + "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", + "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/pathe": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-0.2.0.tgz", + "integrity": "sha512-sTitTPYnn23esFR3RlqYBWn4c45WGeLcsKzQiUpXJAyfcWkolvlYpV8FLo7JishK946oQwMFUCHXQ9AjGPKExw==", + "dev": true, + "peer": true + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "peer": true, + "engines": { + "node": "*" + } + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkg-types": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.0.1.tgz", + "integrity": "sha512-jHv9HB+Ho7dj6ItwppRDDl0iZRYBD0jsakHXtFgoLr+cHSF6xC+QL54sJmWxyGxOLYSHm0afhXhXcQDQqH9z8g==", + "dev": true, + "peer": true, + "dependencies": { + "jsonc-parser": "^3.2.0", + "mlly": "^1.0.0", + "pathe": "^1.0.0" + } + }, + "node_modules/pkg-types/node_modules/pathe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.0.0.tgz", + "integrity": "sha512-nPdMG0Pd09HuSsr7QOKUXO2Jr9eqaDiZvDwdyIhNG5SHYujkQHYKDfGQkulBxvbDHz8oHLsTgKN86LSwYzSHAg==", + "dev": true, + "peer": true + }, + "node_modules/postcss": { + "version": "8.4.21", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.21.tgz", + "integrity": "sha512-tP7u/Sn/dVxK2NnruI4H9BG+x+Wxz6oeZ1cJ8P6G/PZY0IKk4k/63TDsQf2kQq3+qoJeLm2kIBUNlZe3zgb4Zg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + } + ], + "dependencies": { + "nanoid": "^3.3.4", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "peer": true + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "dev": true, + "peer": true, + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", + "dev": true, + "peer": true + }, + "node_modules/regexp.prototype.flags": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.4.3.tgz", + "integrity": "sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "functions-have-names": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "dev": true, + "dependencies": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rollup": { + "version": "2.79.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.1.tgz", + "integrity": "sha512-uKxbd0IhMZOhjAiD5oAFp7BqvkA4Dv47qpOCtaNvng4HBwdbWtdOh8f5nZNuk2rp51PMGk3bzfWu5oayNEuYnw==", + "dev": true, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=10.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", + "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "peer": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "deprecated": "Please use @jridgewell/sourcemap-codec instead", + "dev": true + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "dev": true, + "peer": true, + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "dev": true, + "peer": true, + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-literal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-1.0.0.tgz", + "integrity": "sha512-5o4LsH1lzBzO9UFH63AJ2ad2/S2AVx6NtjOcaz+VTT2h1RiRvbipW72z8M/lxEhcPHDBQwpDrnTF7sXy/7OwCQ==", + "dev": true, + "peer": true, + "dependencies": { + "acorn": "^8.8.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "peer": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tinybench": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.3.1.tgz", + "integrity": "sha512-hGYWYBMPr7p4g5IarQE7XhlyWveh1EKhy4wUBS1LrHXCKYgvz+4/jCqgmJqZxxldesn05vccrtME2RLLZNW7iA==", + "dev": true, + "peer": true + }, + "node_modules/tinypool": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-0.3.0.tgz", + "integrity": "sha512-NX5KeqHOBZU6Bc0xj9Vr5Szbb1j8tUHIeD18s41aDJaPeC5QTdEhK0SpdpUrZlj2nv5cctNcSjaKNanXlfcVEQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-1.0.2.tgz", + "integrity": "sha512-bSGlgwLBYf7PnUsQ6WOc6SJ3pGOcd+d8AA6EUnLDDM0kWEstC1JIlSZA3UNliDXhd9ABoS7hiRBDCu+XP/sf1Q==", + "dev": true, + "peer": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/to-regex-range": { + "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, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/ufo": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.0.1.tgz", + "integrity": "sha512-boAm74ubXHY7KJQZLlXrtMz52qFvpsbOxDcZOnw/Wf+LS4Mmyu7JxmzD4tDLtUQtmZECypJ0FrCz4QIe6dvKRA==", + "dev": true, + "peer": true + }, + "node_modules/vite": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-3.2.5.tgz", + "integrity": "sha512-4mVEpXpSOgrssFZAOmGIr85wPHKvaDAcXqxVxVRZhljkJOMZi1ibLibzjLHzJvcok8BMguLc7g1W6W/GqZbLdQ==", + "dev": true, + "dependencies": { + "esbuild": "^0.15.9", + "postcss": "^8.4.18", + "resolve": "^1.22.1", + "rollup": "^2.79.1" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "peerDependencies": { + "@types/node": ">= 14", + "less": "*", + "sass": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-0.27.0.tgz", + "integrity": "sha512-O1o9joT0qCGx5Om6W0VNLr7M00ttrnFlfZX2d+oxt2T9oZ9DvYSv8kDRhNJDVhAgNgUm3Tc0h/+jppNf3mVKbA==", + "dev": true, + "peer": true, + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.3.4", + "mlly": "^1.0.0", + "pathe": "^0.2.0", + "picocolors": "^1.0.0", + "source-map": "^0.6.1", + "source-map-support": "^0.5.21", + "vite": "^3.0.0 || ^4.0.0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": ">=v14.16.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/vite-plugin-imba": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/vite-plugin-imba/-/vite-plugin-imba-0.10.1.tgz", + "integrity": "sha512-L4YKjsg5h5PPJRmLFw/68beerBRzCGiSjCqe0Xxh1aavvcAL57ZgT+7Y2kvwG7rcFO1YBdWtJ/tyJEsMK7rEAg==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^4.2.1", + "cross-env": "^7.0.3", + "debug": "^4.3.4", + "deepmerge": "^4.2.2", + "diff": "^5.1.0", + "kleur": "^4.1.5", + "magic-string": "^0.26.2" + }, + "engines": { + "node": "^14.18.0 || >= 16" + }, + "peerDependencies": { + "diff-match-patch": "^1.0.5", + "imba": "*", + "vite": "^3.0.0" + }, + "peerDependenciesMeta": { + "diff-match-patch": { + "optional": true + } + } + }, + "node_modules/vite-plugin-imba/node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/vitest": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-0.27.0.tgz", + "integrity": "sha512-BnOa7T6CnXVC6UgcAsvFOZ2Dtvqkt+/Nl6CRgh4qVT70vElf65XwEL6zMRyTF+h2QXJziEkxYdrLo5WCxckMLQ==", + "dev": true, + "peer": true, + "dependencies": { + "@types/chai": "^4.3.4", + "@types/chai-subset": "^1.3.3", + "@types/node": "*", + "acorn": "^8.8.1", + "acorn-walk": "^8.2.0", + "cac": "^6.7.14", + "chai": "^4.3.7", + "debug": "^4.3.4", + "local-pkg": "^0.4.2", + "picocolors": "^1.0.0", + "source-map": "^0.6.1", + "strip-literal": "^1.0.0", + "tinybench": "^2.3.1", + "tinypool": "^0.3.0", + "tinyspy": "^1.0.2", + "vite": "^3.0.0 || ^4.0.0", + "vite-node": "0.27.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": ">=v14.16.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@vitest/browser": "*", + "@vitest/ui": "*", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "dev": true, + "peer": true, + "dependencies": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.1.tgz", + "integrity": "sha512-W8xeTUwaln8i3K/cY1nGXzdnVZlidBcagyNFtBdD5kxnb4TvGKR7FfSIS3mYpwWS1QUCutfKz8IY8RjftB0+1A==", + "dev": true, + "peer": true, + "dependencies": { + "is-map": "^2.0.1", + "is-set": "^2.0.1", + "is-weakmap": "^2.0.1", + "is-weakset": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.9.tgz", + "integrity": "sha512-w9c4xkx6mPidwp7180ckYWfMmvxpjlZuIudNtDf4N/tTAUB8VJbX25qZoAsrtGuYNnGw3pa0AXgbGKRB8/EceA==", + "dev": true, + "peer": true, + "dependencies": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0", + "is-typed-array": "^1.1.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/node_modules/@adobe/css-tools/History.md b/node_modules/@adobe/css-tools/History.md new file mode 100644 index 0000000..ab51baf --- /dev/null +++ b/node_modules/@adobe/css-tools/History.md @@ -0,0 +1,89 @@ +4.0.1 / 2022-08-03 +================== + + * Change globalThis configuration for webpack so UMD module could be used in nodejs (jest-dom) + +4.0.0 / 2022-06-09 +================== + + * Adobe fork of css into @adobe/css + * Convert the project into typescript + * Optimization of performance (+25% in some cases) + * Update all deps + * Remove sourcemap support + +2.2.1 / 2015-06-17 +================== + + * fix parsing escaped quotes in quoted strings + +2.2.0 / 2015-02-18 +================== + + * add `parsingErrors` to list errors when parsing with `silent: true` + * accept EOL characters and all other whitespace characters in `@` rules such + as `@media` + +2.1.0 / 2014-08-05 +================== + + * change error message format and add `.reason` property to errors + * add `inputSourcemaps` option to disable input source map processing + * use `inherits` for inheritance (fixes some browsers) + * add `sourcemap: 'generator'` option to return the `SourceMapGenerator` + object + +2.0.0 / 2014-06-18 +================== + + * add non-enumerable parent reference to each node + * drop Component(1) support + * add support for @custom-media, @host, and @font-face + * allow commas inside selector functions + * allow empty property values + * changed default options.position value to true + * remove comments from properties and values + * asserts when selectors are missing + * added node.position.content property + * absorb css-parse and css-stringify libraries + * apply original source maps from source files + +1.6.1 / 2014-01-02 +================== + + * fix component.json + +1.6.0 / 2013-12-21 +================== + + * update deps + +1.5.0 / 2013-12-03 +================== + + * update deps + +1.1.0 / 2013-04-04 +================== + + * update deps + +1.0.7 / 2012-11-21 +================== + + * fix component.json + +1.0.4 / 2012-11-15 +================== + + * update css-stringify + +1.0.3 / 2012-09-01 +================== + + * add component support + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/@adobe/css-tools/LICENSE b/node_modules/@adobe/css-tools/LICENSE new file mode 100644 index 0000000..e63de06 --- /dev/null +++ b/node_modules/@adobe/css-tools/LICENSE @@ -0,0 +1,10 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2022 Jean-Philippe Zolesio + +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/@adobe/css-tools/Readme.md b/node_modules/@adobe/css-tools/Readme.md new file mode 100644 index 0000000..2eef21a --- /dev/null +++ b/node_modules/@adobe/css-tools/Readme.md @@ -0,0 +1,304 @@ +# @adobe/css-tools + +> This is a fork of the npm css package due to low maintenance + +CSS parser / stringifier. + +## Installation + + $ npm install css + +## Usage + +```js +var css = require('css'); +var obj = css.parse('body { font-size: 12px; }', options); +css.stringify(obj, options); +``` + +## API + +### css.parse(code, [options]) + +Accepts a CSS string and returns an AST `object`. + +`options`: + +- silent: silently fail on parse errors. +- source: the path to the file containing `css`. Makes errors and source + maps more helpful, by letting them know where code comes from. + +### css.stringify(object, [options]) + +Accepts an AST `object` (as `css.parse` produces) and returns a CSS string. + +`options`: + +- indent: the string used to indent the output. Defaults to two spaces. +- compress: omit comments and extraneous whitespace. + +### Example + +```js +var ast = css.parse('body { font-size: 12px; }', { source: 'source.css' }); + +var css = css.stringify(ast); +``` + +### Errors + +Errors thrown during parsing have the following properties: + +- message: `String`. The full error message with the source position. +- reason: `String`. The error message without position. +- filename: `String` or `undefined`. The value of `options.source` if + passed to `css.parse`. Otherwise `undefined`. +- line: `Integer`. +- column: `Integer`. +- source: `String`. The portion of code that couldn't be parsed. + +When parsing with the `silent` option, errors are listed in the +`parsingErrors` property of the [`stylesheet`](#stylesheet) node instead +of being thrown. + +If you create any errors in plugins such as in +[rework](https://github.com/reworkcss/rework), you __must__ set the same +properties for consistency. + +## AST + +Interactively explore the AST with . + +### Common properties + +All nodes have the following properties. + +#### position + +Information about the position in the source string that corresponds to +the node. + +`Object`: + +- start: `Object`: + - line: `Number`. + - column: `Number`. +- end: `Object`: + - line: `Number`. + - column: `Number`. +- source: `String` or `undefined`. The value of `options.source` if passed to + `css.parse`. Otherwise `undefined`. +- content: `String`. The full source string passed to `css.parse`. + +The line and column numbers are 1-based: The first line is 1 and the first +column of a line is 1 (not 0). + +The `position` property lets you know from which source file the node comes +from (if available), what that file contains, and what part of that file was +parsed into the node. + +#### type + +`String`. The possible values are the ones listed in the Types section below. + +#### parent + +A reference to the parent node, or `null` if the node has no parent. + +### Types + +The available values of `node.type` are listed below, as well as the available +properties of each node (other than the common properties listed above.) + +#### stylesheet + +The root node returned by `css.parse`. + +- stylesheet: `Object`: + - rules: `Array` of nodes with the types `rule`, `comment` and any of the + at-rule types. + - parsingErrors: `Array` of `Error`s. Errors collected during parsing when + option `silent` is true. + +#### rule + +- selectors: `Array` of `String`s. The list of selectors of the rule, split + on commas. Each selector is trimmed from whitespace and comments. +- declarations: `Array` of nodes with the types `declaration` and `comment`. + +#### declaration + +- property: `String`. The property name, trimmed from whitespace and + comments. May not be empty. +- value: `String`. The value of the property, trimmed from whitespace and + comments. Empty values are allowed. + +#### comment + +A rule-level or declaration-level comment. Comments inside selectors, +properties and values etc. are lost. + +- comment: `String`. The part between the starting `/*` and the ending `*/` + of the comment, including whitespace. + +#### charset + +The `@charset` at-rule. + +- charset: `String`. The part following `@charset `. + +#### custom-media + +The `@custom-media` at-rule. + +- name: `String`. The `--`-prefixed name. +- media: `String`. The part following the name. + +#### document + +The `@document` at-rule. + +- document: `String`. The part following `@document `. +- vendor: `String` or `undefined`. The vendor prefix in `@document`, or + `undefined` if there is none. +- rules: `Array` of nodes with the types `rule`, `comment` and any of the + at-rule types. + +#### font-face + +The `@font-face` at-rule. + +- declarations: `Array` of nodes with the types `declaration` and `comment`. + +#### host + +The `@host` at-rule. + +- rules: `Array` of nodes with the types `rule`, `comment` and any of the + at-rule types. + +#### import + +The `@import` at-rule. + +- import: `String`. The part following `@import `. + +#### keyframes + +The `@keyframes` at-rule. + +- name: `String`. The name of the keyframes rule. +- vendor: `String` or `undefined`. The vendor prefix in `@keyframes`, or + `undefined` if there is none. +- keyframes: `Array` of nodes with the types `keyframe` and `comment`. + +#### keyframe + +- values: `Array` of `String`s. The list of “selectors” of the keyframe rule, + split on commas. Each “selector” is trimmed from whitespace. +- declarations: `Array` of nodes with the types `declaration` and `comment`. + +#### media + +The `@media` at-rule. + +- media: `String`. The part following `@media `. +- rules: `Array` of nodes with the types `rule`, `comment` and any of the + at-rule types. + +#### namespace + +The `@namespace` at-rule. + +- namespace: `String`. The part following `@namespace `. + +#### page + +The `@page` at-rule. + +- selectors: `Array` of `String`s. The list of selectors of the rule, split + on commas. Each selector is trimmed from whitespace and comments. +- declarations: `Array` of nodes with the types `declaration` and `comment`. + +#### supports + +The `@supports` at-rule. + +- supports: `String`. The part following `@supports `. +- rules: `Array` of nodes with the types `rule`, `comment` and any of the + at-rule types. + +### Example + +CSS: + +```css +body { + background: #eee; + color: #888; +} +``` + +Parse tree: + +```json +{ + "type": "stylesheet", + "stylesheet": { + "rules": [ + { + "type": "rule", + "selectors": [ + "body" + ], + "declarations": [ + { + "type": "declaration", + "property": "background", + "value": "#eee", + "position": { + "start": { + "line": 2, + "column": 3 + }, + "end": { + "line": 2, + "column": 19 + } + } + }, + { + "type": "declaration", + "property": "color", + "value": "#888", + "position": { + "start": { + "line": 3, + "column": 3 + }, + "end": { + "line": 3, + "column": 14 + } + } + } + ], + "position": { + "start": { + "line": 1, + "column": 1 + }, + "end": { + "line": 4, + "column": 2 + } + } + } + ] + } +} +``` + +## License + +MIT diff --git a/node_modules/@adobe/css-tools/dist/cjs/CssParseError.d.ts b/node_modules/@adobe/css-tools/dist/cjs/CssParseError.d.ts new file mode 100644 index 0000000..987d91b --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/CssParseError.d.ts @@ -0,0 +1,8 @@ +export default class CssParseError extends Error { + readonly reason: string; + readonly filename?: string; + readonly line: number; + readonly column: number; + readonly source: string; + constructor(filename: string, msg: string, lineno: number, column: number, css: string); +} diff --git a/node_modules/@adobe/css-tools/dist/cjs/CssPosition.d.ts b/node_modules/@adobe/css-tools/dist/cjs/CssPosition.d.ts new file mode 100644 index 0000000..1aac013 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/CssPosition.d.ts @@ -0,0 +1,21 @@ +/** + * Store position information for a node + */ +export default class Position { + start: { + line: number; + column: number; + }; + end: { + line: number; + column: number; + }; + source?: string; + constructor(start: { + line: number; + column: number; + }, end: { + line: number; + column: number; + }, source: string); +} diff --git a/node_modules/@adobe/css-tools/dist/cjs/cssTools.js b/node_modules/@adobe/css-tools/dist/cjs/cssTools.js new file mode 100644 index 0000000..7f75f81 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/cssTools.js @@ -0,0 +1,2 @@ +(()=>{"use strict";var t={831:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});class s extends Error{constructor(t,e,s,i,n){super(t+":"+s+":"+i+": "+e),this.reason=e,this.filename=t,this.line=s,this.column=i,this.source=n}}e.default=s},711:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class{constructor(t,e,s){this.start=t,this.end=e,this.source=s}}},607:function(t,e,s){var i=this&&this.__createBinding||(Object.create?function(t,e,s,i){void 0===i&&(i=s);var n=Object.getOwnPropertyDescriptor(e,s);n&&!("get"in n?!e.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return e[s]}}),Object.defineProperty(t,i,n)}:function(t,e,s,i){void 0===i&&(i=s),t[i]=e[s]}),n=this&&this.__exportStar||function(t,e){for(var s in t)"default"===s||Object.prototype.hasOwnProperty.call(e,s)||i(e,t,s)};Object.defineProperty(e,"__esModule",{value:!0}),e.stringify=e.parse=void 0;var r=s(654);Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return r.default}});var o=s(373);Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return o.default}}),n(s(371),e),n(s(831),e),n(s(711),e)},654:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parse=void 0;const i=s(831),n=s(711),r=s(371),o=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;function c(t){return t?t.trim():""}function u(t,e){const s=t&&"string"==typeof t.type,i=s?t:e;for(const e in t){const s=t[e];Array.isArray(s)?s.forEach((t=>{u(t,i)})):s&&"object"==typeof s&&u(s,i)}return s&&Object.defineProperty(t,"parent",{configurable:!0,writable:!0,enumerable:!1,value:e||null}),t}e.parse=(t,e)=>{e=e||{};let s=1,a=1;function m(){const t={line:s,column:a};return function(i){return i.position=new n.default(t,{line:s,column:a},(null==e?void 0:e.source)||""),g(),i}}const p=[];function h(n){const r=new i.default((null==e?void 0:e.source)||"",n,s,a,t);if(!(null==e?void 0:e.silent))throw r;p.push(r)}function l(){return y(/^{\s*/)}function f(){return y(/^}/)}function d(){let e;const s=[];for(g(),v(s);t.length&&"}"!==t.charAt(0)&&(e=M()||P());)e&&(s.push(e),v(s));return s}function y(e){const i=e.exec(t);if(!i)return;const n=i[0];return function(t){const e=t.match(/\n/g);e&&(s+=e.length);const i=t.lastIndexOf("\n");a=~i?t.length-i:a+t.length}(n),t=t.slice(n.length),i}function g(){y(/^\s*/)}function v(t){let e;for(t=t||[];e=C();)e&&t.push(e);return t}function C(){const e=m();if("/"!==t.charAt(0)||"*"!==t.charAt(1))return;const s=y(/^\/\*[^]*?\*\//);return s?e({type:r.CssTypes.comment,comment:s[0].slice(2,-2)}):h("End of comment missing")}function T(){const t=y(/^([^{]+)/);if(!t)return;const e=c(t[0]).replace(/\/\*[^]*?\*\//gm,"");return-1===e.indexOf(",")?[e]:e.replace(/("|')(?:\\\1|.)*?,(?:\\\1|.)*?\1|\(.*?,.*?\)/g,(t=>t.replace(/,/g,"‌"))).split(",").map((t=>c(t.replace(/\u200C/g,","))))}function b(){const t=m(),e=y(/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);if(!e)return;const s=c(e[0]);if(!y(/^:\s*/))return h("property missing ':'");const i=y(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/),n=t({type:r.CssTypes.declaration,property:s.replace(o,""),value:i?c(i[0]).replace(o,""):""});return y(/^[;\s]*/),n}function j(){const t=[];if(!l())return h("missing '{'");let e;for(v(t);e=b();)e&&(t.push(e),v(t));return f()?t:h("missing '}'")}function k(){let t;const e=[],s=m();for(;t=y(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/);)e.push(t[1]),y(/^,\s*/);if(e.length)return s({type:r.CssTypes.keyframe,values:e,declarations:j()||[]})}const _=w("import"),V=w("charset"),O=w("namespace");function w(t){const e=new RegExp("^@"+t+"\\s*([^;]+);");return function(){const s=m(),i=y(e);if(!i)return;const n={type:t};return n[t]=i[1].trim(),s(n)}}function M(){if("@"===t[0])return function(){const t=m(),e=y(/^@([-\w]+)?keyframes\s*/);if(!e)return;const s=e[1],i=y(/^([-\w]+)\s*/);if(!i)return h("@keyframes missing name");const n=i[1];if(!l())return h("@keyframes missing '{'");let o,c=v();for(;o=k();)c.push(o),c=c.concat(v());return f()?t({type:r.CssTypes.keyframes,name:n,vendor:s,keyframes:c}):h("@keyframes missing '}'")}()||function(){const t=m(),e=y(/^@media *([^{]+)/);if(!e)return;const s=c(e[1]);if(!l())return h("@media missing '{'");const i=v().concat(d());return f()?t({type:r.CssTypes.media,media:s,rules:i}):h("@media missing '}'")}()||function(){const t=m(),e=y(/^@custom-media\s+(--[^\s]+)\s*([^{;]+);/);if(e)return t({type:r.CssTypes.customMedia,name:c(e[1]),media:c(e[2])})}()||function(){const t=m(),e=y(/^@supports *([^{]+)/);if(!e)return;const s=c(e[1]);if(!l())return h("@supports missing '{'");const i=v().concat(d());return f()?t({type:r.CssTypes.supports,supports:s,rules:i}):h("@supports missing '}'")}()||_()||V()||O()||function(){const t=m(),e=y(/^@([-\w]+)?document *([^{]+)/);if(!e)return;const s=c(e[1]),i=c(e[2]);if(!l())return h("@document missing '{'");const n=v().concat(d());return f()?t({type:r.CssTypes.document,document:i,vendor:s,rules:n}):h("@document missing '}'")}()||function(){const t=m();if(!y(/^@page */))return;const e=T()||[];if(!l())return h("@page missing '{'");let s,i=v();for(;s=b();)i.push(s),i=i.concat(v());return f()?t({type:r.CssTypes.page,selectors:e,declarations:i}):h("@page missing '}'")}()||function(){const t=m();if(!y(/^@host\s*/))return;if(!l())return h("@host missing '{'");const e=v().concat(d());return f()?t({type:r.CssTypes.host,rules:e}):h("@host missing '}'")}()||function(){const t=m();if(!y(/^@font-face\s*/))return;if(!l())return h("@font-face missing '{'");let e,s=v();for(;e=b();)s.push(e),s=s.concat(v());return f()?t({type:r.CssTypes.fontFace,declarations:s}):h("@font-face missing '}'")}()}function P(){const t=m(),e=T();return e?(v(),t({type:r.CssTypes.rule,selectors:e,declarations:j()||[]})):h("selector missing")}return u(function(){const t=d();return{type:r.CssTypes.stylesheet,stylesheet:{source:null==e?void 0:e.source,rules:t,parsingErrors:p}}}())},e.default=e.parse},854:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});const i=s(371);e.default=class{constructor(t){this.level=0,this.indentation=" ",this.compress=!1,"string"==typeof(null==t?void 0:t.indent)&&(this.indentation=null==t?void 0:t.indent),(null==t?void 0:t.compress)&&(this.compress=!0)}emit(t,e){return t}indent(t){return this.level=this.level||1,t?(this.level+=t,""):Array(this.level).join(this.indentation)}visit(t){switch(t.type){case i.CssTypes.stylesheet:return this.stylesheet(t);case i.CssTypes.rule:return this.rule(t);case i.CssTypes.declaration:return this.declaration(t);case i.CssTypes.comment:return this.comment(t);case i.CssTypes.charset:return this.charset(t);case i.CssTypes.document:return this.document(t);case i.CssTypes.customMedia:return this.customMedia(t);case i.CssTypes.fontFace:return this.fontFace(t);case i.CssTypes.host:return this.host(t);case i.CssTypes.import:return this.import(t);case i.CssTypes.keyframes:return this.keyframes(t);case i.CssTypes.keyframe:return this.keyframe(t);case i.CssTypes.media:return this.media(t);case i.CssTypes.namespace:return this.namespace(t);case i.CssTypes.page:return this.page(t);case i.CssTypes.supports:return this.supports(t)}}mapVisit(t,e){let s="";e=e||"";for(let i=0,n=t.length;is+t)).join(",\n"),t.position)+this.emit(" {\n")+this.emit(this.indent(1))+this.mapVisit(e,"\n")+this.emit(this.indent(-1))+this.emit("\n"+this.indent()+"}")}declaration(t){return this.compress?this.emit(t.property+":"+t.value,t.position)+this.emit(";"):this.emit(this.indent())+this.emit(t.property+": "+t.value,t.position)+this.emit(";")}}},373:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});const i=s(854);e.default=(t,e)=>new i.default(e||{}).compile(t)},371:(t,e)=>{var s;Object.defineProperty(e,"__esModule",{value:!0}),e.CssTypes=void 0,(s=e.CssTypes||(e.CssTypes={})).stylesheet="stylesheet",s.rule="rule",s.declaration="declaration",s.comment="comment",s.charset="charset",s.document="document",s.customMedia="custom-media",s.fontFace="font-face",s.host="host",s.import="import",s.keyframes="keyframes",s.keyframe="keyframe",s.media="media",s.namespace="namespace",s.page="page",s.supports="supports"}},e={},s=function s(i){var n=e[i];if(void 0!==n)return n.exports;var r=e[i]={exports:{}};return t[i].call(r.exports,r,r.exports,s),r.exports}(607);module.exports=s})(); +//# sourceMappingURL=cssTools.js.map \ No newline at end of file diff --git a/node_modules/@adobe/css-tools/dist/cjs/cssTools.js.map b/node_modules/@adobe/css-tools/dist/cjs/cssTools.js.map new file mode 100644 index 0000000..5b13ed0 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/cssTools.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cssTools.js","mappings":"uFAAA,MAAqBA,UAAsBC,MAOzCC,YACEC,EACAC,EACAC,EACAC,EACAC,GAEAC,MAAML,EAAW,IAAME,EAAS,IAAMC,EAAS,KAAOF,GACtDK,KAAKC,OAASN,EACdK,KAAKN,SAAWA,EAChBM,KAAKE,KAAON,EACZI,KAAKH,OAASA,EACdG,KAAKG,OAASL,CAChB,EApBF,W,+DCGA,gBAKEL,YACEW,EACAC,EACAF,GAEAH,KAAKI,MAAQA,EACbJ,KAAKK,IAAMA,EACXL,KAAKG,OAASA,CAChB,E,shBChBF,aAAQ,uEAAAG,OAAO,IACf,aAAQ,2EAAAA,OAAO,IACf,YACA,YACA,W,gFCJA,eACA,SACA,SAwBMC,EAAY,kCAqnBlB,SAASC,EAAKC,GACZ,OAAOA,EAAMA,EAAID,OAAS,EAC5B,CAKA,SAASE,EAAsCC,EAASC,GACtD,MAAMC,EAASF,GAA2B,iBAAbA,EAAIG,KAC3BC,EAAcF,EAASF,EAAMC,EAEnC,IAAK,MAAMI,KAAKL,EAAK,CACnB,MAAMM,EAAQN,EAAIK,GACdE,MAAMC,QAAQF,GAChBA,EAAMG,SAAQC,IACZX,EAAUW,EAAGN,EAAY,IAElBE,GAA0B,iBAAVA,GACzBP,EAAUO,EAAOF,E,CAarB,OATIF,GACFS,OAAOC,eAAeZ,EAAK,SAAU,CACnCa,cAAc,EACdC,UAAU,EACVC,YAAY,EACZT,MAAOL,GAAU,OAIdD,CACT,CAnpBa,EAAAgB,MAAQ,CACnB7B,EACA8B,KAEAA,EAAUA,GAAW,CAAC,EAKtB,IAAIhC,EAAS,EACTC,EAAS,EAeb,SAASgC,IACP,MAAMzB,EAAQ,CAACF,KAAMN,EAAQC,OAAQA,GACrC,OAAO,SACLiC,GAQA,OANCA,EAAYD,SAAW,IAAI,UAC1BzB,EACA,CAACF,KAAMN,EAAQC,OAAQA,IACvB+B,aAAO,EAAPA,EAASzB,SAAU,IAErB4B,IACOD,CACT,CACF,CAKA,MAAME,EAAmC,GAEzC,SAASC,EAAMtC,GACb,MAAMuC,EAAM,IAAI,WACdN,aAAO,EAAPA,EAASzB,SAAU,GACnBR,EACAC,EACAC,EACAC,GAGF,KAAI8B,aAAO,EAAPA,EAASO,QAGX,MAAMD,EAFNF,EAAWI,KAAKF,EAIpB,CAuBA,SAASG,IACP,OAAOC,EAAM,QACf,CAKA,SAASC,IACP,OAAOD,EAAM,KACf,CAKA,SAASE,IACP,IAAIV,EACJ,MAAMU,EAA0C,GAGhD,IAFAT,IACAU,EAASD,GACF1C,EAAI4C,QAA4B,MAAlB5C,EAAI6C,OAAO,KAAeb,EAAOc,KAAYC,MAC5Df,IACFU,EAAMJ,KAAKN,GACXW,EAASD,IAGb,OAAOA,CACT,CAKA,SAASF,EAAMQ,GACb,MAAMC,EAAID,EAAGE,KAAKlD,GAClB,IAAKiD,EACH,OAEF,MAAMtC,EAAMsC,EAAE,GAGd,OA1GF,SAAwBtC,GACtB,MAAMwC,EAAQxC,EAAI6B,MAAM,OACpBW,IAAOrD,GAAUqD,EAAMP,QAC3B,MAAMQ,EAAIzC,EAAI0C,YAAY,MAC1BtD,GAAUqD,EAAIzC,EAAIiC,OAASQ,EAAIrD,EAASY,EAAIiC,MAC9C,CAmGEU,CAAe3C,GACfX,EAAMA,EAAIuD,MAAM5C,EAAIiC,QACbK,CACT,CAKA,SAAShB,IACPO,EAAM,OACR,CAKA,SAASG,EACPD,GAEA,IAAIc,EAEJ,IADAd,EAAQA,GAAS,GACTc,EAAIC,KACND,GACFd,EAAMJ,KAAKkB,GAGf,OAAOd,CACT,CAKA,SAASe,IACP,MAAMC,EAAM3B,IACZ,GAAI,MAAQ/B,EAAI6C,OAAO,IAAM,MAAQ7C,EAAI6C,OAAO,GAC9C,OAGF,MAAMI,EAAIT,EAAM,kBAChB,OAAKS,EAIES,EAAmB,CACxB1C,KAAM,EAAA2C,SAASF,QACfA,QAASR,EAAE,GAAGM,MAAM,GAAI,KALjBpB,EAAM,yBAOjB,CAKA,SAASyB,IACP,MAAMX,EAAIT,EAAM,YAChB,IAAKS,EACH,OAIF,MAAMY,EAAMnD,EAAKuC,EAAE,IAAIa,QAAQ,kBAAmB,IAGlD,OAA0B,IAAtBD,EAAIE,QAAQ,KACP,CAACF,GAIRA,EAuBGC,QAAQ,iDAAiDb,GACxDA,EAAEa,QAAQ,KAAM,OAGjBE,MAAM,KAENC,KAAIC,GACIxD,EAAKwD,EAAEJ,QAAQ,UAAW,OAGzC,CAKA,SAASK,IACP,MAAMT,EAAM3B,IAGNqC,EAAY5B,EAAM,0CACxB,IAAK4B,EACH,OAEF,MAAMC,EAAY3D,EAAK0D,EAAU,IAGjC,IAAK5B,EAAM,SACT,OAAOL,EAAM,wBAIf,MAAMmC,EAAM9B,EAAM,wDAEZ+B,EAAMb,EAAuB,CACjC1C,KAAM,EAAA2C,SAASQ,YACfK,SAAUH,EAAUP,QAAQrD,EAAW,IACvCU,MAAOmD,EAAM5D,EAAK4D,EAAI,IAAIR,QAAQrD,EAAW,IAAM,KAMrD,OAFA+B,EAAM,WAEC+B,CACT,CAKA,SAASE,IACP,MAAMC,EAAkD,GAExD,IAAKnC,IACH,OAAOJ,EAAM,eAKf,IAAIwC,EACJ,IAJAhC,EAAS+B,GAIDC,EAAOR,KACTQ,IACFD,EAAMpC,KAAKqC,GACXhC,EAAS+B,IAIb,OAAKjC,IAGEiC,EAFEvC,EAAM,cAGjB,CAKA,SAASyC,IACP,IAAI3B,EACJ,MAAM4B,EAAO,GACPnB,EAAM3B,IAEZ,KAAQkB,EAAIT,EAAM,wCAChBqC,EAAKvC,KAAKW,EAAE,IACZT,EAAM,SAGR,GAAKqC,EAAKjC,OAIV,OAAOc,EAAoB,CACzB1C,KAAM,EAAA2C,SAASiB,SACfE,OAAQD,EACRJ,aAAcA,KAAkB,IAEpC,CAuPA,MAAMM,EAAWC,EAA6B,UAKxCC,EAAYD,EAA8B,WAK1CE,EAAcF,EAAgC,aAKpD,SAASA,EACPG,GAEA,MAAMnC,EAAK,IAAIoC,OAAO,KAAOD,EAAO,gBACpC,OAAO,WACL,MAAMzB,EAAM3B,IACNkB,EAAIT,EAAMQ,GAChB,IAAKC,EACH,OAEF,MAAMsB,EAA8B,CAACvD,KAAMmE,GAE3C,OADAZ,EAAIY,GAAQlC,EAAE,GAAGvC,OACVgD,EAAQa,EACjB,CACF,CAKA,SAASzB,IACP,GAAe,MAAX9C,EAAI,GAIR,OAzRF,WACE,MAAM0D,EAAM3B,IACNsD,EAAK7C,EAAM,2BAEjB,IAAK6C,EACH,OAEF,MAAMC,EAASD,EAAG,GAGZE,EAAK/C,EAAM,gBACjB,IAAK+C,EACH,OAAOpD,EAAM,2BAEf,MAAMgD,EAAOI,EAAG,GAEhB,IAAKhD,IACH,OAAOJ,EAAM,0BAGf,IAAIqD,EACAC,EAAgD9C,IACpD,KAAQ6C,EAAQZ,KACda,EAAOnD,KAAKkD,GACZC,EAASA,EAAOC,OAAO/C,KAGzB,OAAKF,IAIEiB,EAAqB,CAC1B1C,KAAM,EAAA2C,SAASgC,UACfR,KAAMA,EACNG,OAAQA,EACRK,UAAWF,IAPJtD,EAAM,yBASjB,CAqPIyD,IAxLJ,WACE,MAAMlC,EAAM3B,IACNkB,EAAIT,EAAM,oBAEhB,IAAKS,EACH,OAEF,MAAM4C,EAAQnF,EAAKuC,EAAE,IAErB,IAAKV,IACH,OAAOJ,EAAM,sBAGf,MAAM2D,EAAQnD,IAAyB+C,OAAOhD,KAE9C,OAAKD,IAIEiB,EAAiB,CACtB1C,KAAM,EAAA2C,SAASkC,MACfA,MAAOA,EACPnD,MAAOoD,IANA3D,EAAM,qBAQjB,CAiKI4D,IA5JJ,WACE,MAAMrC,EAAM3B,IACNkB,EAAIT,EAAM,2CAChB,GAAKS,EAIL,OAAOS,EAAuB,CAC5B1C,KAAM,EAAA2C,SAASqC,YACfb,KAAMzE,EAAKuC,EAAE,IACb4C,MAAOnF,EAAKuC,EAAE,KAElB,CAiJIgD,IAlPJ,WACE,MAAMvC,EAAM3B,IACNkB,EAAIT,EAAM,uBAEhB,IAAKS,EACH,OAEF,MAAMiD,EAAWxF,EAAKuC,EAAE,IAExB,IAAKV,IACH,OAAOJ,EAAM,yBAGf,MAAM2D,EAAQnD,IAAyB+C,OAAOhD,KAE9C,OAAKD,IAIEiB,EAAoB,CACzB1C,KAAM,EAAA2C,SAASuC,SACfA,SAAUA,EACVxD,MAAOoD,IANA3D,EAAM,wBAQjB,CA2NIgE,IACApB,KACAE,KACAC,KA7GJ,WACE,MAAMxB,EAAM3B,IACNkB,EAAIT,EAAM,gCAChB,IAAKS,EACH,OAGF,MAAMqC,EAAS5E,EAAKuC,EAAE,IAChBmD,EAAM1F,EAAKuC,EAAE,IAEnB,IAAKV,IACH,OAAOJ,EAAM,yBAGf,MAAM2D,EAAQnD,IAAyB+C,OAAOhD,KAE9C,OAAKD,IAIEiB,EAAoB,CACzB1C,KAAM,EAAA2C,SAAS0C,SACfA,SAAUD,EACVd,OAAQA,EACR5C,MAAOoD,IAPA3D,EAAM,wBASjB,CAoFImE,IAjJJ,WACE,MAAM5C,EAAM3B,IAEZ,IADUS,EAAM,YAEd,OAGF,MAAM+D,EAAM3C,KAAc,GAE1B,IAAKrB,IACH,OAAOJ,EAAM,qBAEf,IAGIwC,EAHAD,EAAQ/B,IAIZ,KAAQgC,EAAOR,KACbO,EAAMpC,KAAKqC,GACXD,EAAQA,EAAMgB,OAAO/C,KAGvB,OAAKF,IAIEiB,EAAgB,CACrB1C,KAAM,EAAA2C,SAAS6C,KACfC,UAAWF,EACX9B,aAAcC,IANPvC,EAAM,oBAQjB,CAoHIuE,IA3NJ,WACE,MAAMhD,EAAM3B,IAGZ,IAFUS,EAAM,aAGd,OAGF,IAAKD,IACH,OAAOJ,EAAM,qBAGf,MAAM2D,EAAQnD,IAAyB+C,OAAOhD,KAE9C,OAAKD,IAIEiB,EAAgB,CACrB1C,KAAM,EAAA2C,SAASgD,KACfjE,MAAOoD,IALA3D,EAAM,oBAOjB,CAsMIyE,IAjFJ,WACE,MAAMlD,EAAM3B,IAEZ,IADUS,EAAM,kBAEd,OAGF,IAAKD,IACH,OAAOJ,EAAM,0BAEf,IAGIwC,EAHAD,EAAQ/B,IAIZ,KAAQgC,EAAOR,KACbO,EAAMpC,KAAKqC,GACXD,EAAQA,EAAMgB,OAAO/C,KAGvB,OAAKF,IAIEiB,EAAoB,CACzB1C,KAAM,EAAA2C,SAASkD,SACfpC,aAAcC,IALPvC,EAAM,yBAOjB,CAuDI2E,EAEJ,CAKA,SAAS/D,IACP,MAAMW,EAAM3B,IACNwE,EAAM3C,IAEZ,OAAK2C,GAGL5D,IAEOe,EAAgB,CACrB1C,KAAM,EAAA2C,SAASZ,KACf0D,UAAWF,EACX9B,aAAcA,KAAkB,MAPzBtC,EAAM,mBASjB,CAEA,OAAOvB,EA7iBP,WACE,MAAMmG,EAAYrE,IAWlB,MATiC,CAC/B1B,KAAM,EAAA2C,SAASqD,WACfA,WAAY,CACV3G,OAAQyB,aAAO,EAAPA,EAASzB,OACjBqC,MAAOqE,EACPE,cAAe/E,GAKrB,CAgiBiB8E,GAAa,EAwChC,UAAe,EAAAnF,K,iECjrBf,eA2YA,UArXA,MAKElC,YAAYmC,GAJZ,KAAAoF,MAAQ,EACR,KAAAC,YAAc,KACd,KAAAC,UAAW,EAGsB,iBAApBtF,aAAO,EAAPA,EAASuF,UAClBnH,KAAKiH,YAAcrF,aAAO,EAAPA,EAASuF,SAE1BvF,aAAO,EAAPA,EAASsF,YACXlH,KAAKkH,UAAW,EAEpB,CAIAE,KAAK3G,EAAa4G,GAChB,OAAO5G,CACT,CAKA0G,OAAOH,GAGL,OAFAhH,KAAKgH,MAAQhH,KAAKgH,OAAS,EAEvBA,GACFhH,KAAKgH,OAASA,EACP,IAGF9F,MAAMlB,KAAKgH,OAAOM,KAAKtH,KAAKiH,YACrC,CAEAM,MAAMzF,GACJ,OAAQA,EAAKhB,MACX,KAAK,EAAA2C,SAASqD,WACZ,OAAO9G,KAAK8G,WAAWhF,GACzB,KAAK,EAAA2B,SAASZ,KACZ,OAAO7C,KAAK6C,KAAKf,GACnB,KAAK,EAAA2B,SAASQ,YACZ,OAAOjE,KAAKiE,YAAYnC,GAC1B,KAAK,EAAA2B,SAASF,QACZ,OAAOvD,KAAKuD,QAAQzB,GACtB,KAAK,EAAA2B,SAAS+D,QACZ,OAAOxH,KAAKwH,QAAQ1F,GACtB,KAAK,EAAA2B,SAAS0C,SACZ,OAAOnG,KAAKmG,SAASrE,GACvB,KAAK,EAAA2B,SAASqC,YACZ,OAAO9F,KAAK8F,YAAYhE,GAC1B,KAAK,EAAA2B,SAASkD,SACZ,OAAO3G,KAAK2G,SAAS7E,GACvB,KAAK,EAAA2B,SAASgD,KACZ,OAAOzG,KAAKyG,KAAK3E,GACnB,KAAK,EAAA2B,SAASgE,OACZ,OAAOzH,KAAKyH,OAAO3F,GACrB,KAAK,EAAA2B,SAASgC,UACZ,OAAOzF,KAAKyF,UAAU3D,GACxB,KAAK,EAAA2B,SAASiB,SACZ,OAAO1E,KAAK0E,SAAS5C,GACvB,KAAK,EAAA2B,SAASkC,MACZ,OAAO3F,KAAK2F,MAAM7D,GACpB,KAAK,EAAA2B,SAASiE,UACZ,OAAO1H,KAAK0H,UAAU5F,GACxB,KAAK,EAAA2B,SAAS6C,KACZ,OAAOtG,KAAKsG,KAAKxE,GACnB,KAAK,EAAA2B,SAASuC,SACZ,OAAOhG,KAAKgG,SAASlE,GAE3B,CAEA6F,SAASC,EAA8BC,GACrC,IAAIC,EAAM,GACVD,EAAQA,GAAS,GAEjB,IAAK,IAAI3E,EAAI,EAAGR,EAASkF,EAAMlF,OAAQQ,EAAIR,EAAQQ,IACjD4E,GAAO9H,KAAKuH,MAAMK,EAAM1E,IACpB2E,GAAS3E,EAAIR,EAAS,IACxBoF,GAAO9H,KAAKoH,KAAKS,IAIrB,OAAOC,CACT,CAEAC,QAAQjG,GACN,OAAI9B,KAAKkH,SACApF,EAAKgF,WAAWtE,MAAMuB,IAAI/D,KAAKuH,MAAOvH,MAAMsH,KAAK,IAGnDtH,KAAK8G,WAAWhF,EACzB,CAKAgF,WAAWhF,GACT,OAAO9B,KAAK2H,SAAS7F,EAAKgF,WAAWtE,MAAO,OAC9C,CAKAe,QAAQzB,GACN,OAAI9B,KAAKkH,SACAlH,KAAKoH,KAAK,GAAItF,EAAKD,UAErB7B,KAAKoH,KAAKpH,KAAKmH,SAAW,KAAOrF,EAAKyB,QAAU,KAAMzB,EAAKD,SACpE,CAKA4F,OAAO3F,GACL,OAAO9B,KAAKoH,KAAK,WAAatF,EAAK2F,OAAS,IAAK3F,EAAKD,SACxD,CAKA8D,MAAM7D,GACJ,OAAI9B,KAAKkH,SAELlH,KAAKoH,KAAK,UAAYtF,EAAK6D,MAAO7D,EAAKD,UACvC7B,KAAKoH,KAAK,KACVpH,KAAK2H,SAAS7F,EAAKU,OACnBxC,KAAKoH,KAAK,KAIZpH,KAAKoH,KAAK,UAAYtF,EAAK6D,MAAO7D,EAAKD,UACvC7B,KAAKoH,KAAK,OAASpH,KAAKmH,OAAO,IAC/BnH,KAAK2H,SAAS7F,EAAKU,MAAO,QAC1BxC,KAAKoH,KAAKpH,KAAKmH,QAAQ,GAAK,MAEhC,CAKAhB,SAASrE,GACP,MAAMoE,EAAM,KAAOpE,EAAKsD,QAAU,IAAM,YAActD,EAAKqE,SAC3D,OAAInG,KAAKkH,SAELlH,KAAKoH,KAAKlB,EAAKpE,EAAKD,UACpB7B,KAAKoH,KAAK,KACVpH,KAAK2H,SAAS7F,EAAKU,OACnBxC,KAAKoH,KAAK,KAIZpH,KAAKoH,KAAKlB,EAAKpE,EAAKD,UACpB7B,KAAKoH,KAAK,QAAepH,KAAKmH,OAAO,IACrCnH,KAAK2H,SAAS7F,EAAKU,MAAO,QAC1BxC,KAAKoH,KAAKpH,KAAKmH,QAAQ,GAAK,MAEhC,CAKAK,QAAQ1F,GACN,OAAO9B,KAAKoH,KAAK,YAActF,EAAK0F,QAAU,IAAK1F,EAAKD,SAC1D,CAKA6F,UAAU5F,GACR,OAAO9B,KAAKoH,KAAK,cAAgBtF,EAAK4F,UAAY,IAAK5F,EAAKD,SAC9D,CAKAmE,SAASlE,GACP,OAAI9B,KAAKkH,SAELlH,KAAKoH,KAAK,aAAetF,EAAKkE,SAAUlE,EAAKD,UAC7C7B,KAAKoH,KAAK,KACVpH,KAAK2H,SAAS7F,EAAKU,OACnBxC,KAAKoH,KAAK,KAIZpH,KAAKoH,KAAK,aAAetF,EAAKkE,SAAUlE,EAAKD,UAC7C7B,KAAKoH,KAAK,OAASpH,KAAKmH,OAAO,IAC/BnH,KAAK2H,SAAS7F,EAAKU,MAAO,QAC1BxC,KAAKoH,KAAKpH,KAAKmH,QAAQ,GAAK,MAEhC,CAKA1B,UAAU3D,GACR,OAAI9B,KAAKkH,SAELlH,KAAKoH,KACH,KAAOtF,EAAKsD,QAAU,IAAM,aAAetD,EAAKmD,KAChDnD,EAAKD,UAEP7B,KAAKoH,KAAK,KACVpH,KAAK2H,SAAS7F,EAAK2D,WACnBzF,KAAKoH,KAAK,KAIZpH,KAAKoH,KACH,KAAOtF,EAAKsD,QAAU,IAAM,aAAetD,EAAKmD,KAChDnD,EAAKD,UAEP7B,KAAKoH,KAAK,OAASpH,KAAKmH,OAAO,IAC/BnH,KAAK2H,SAAS7F,EAAK2D,UAAW,MAC9BzF,KAAKoH,KAAKpH,KAAKmH,QAAQ,GAAK,IAEhC,CAKAzC,SAAS5C,GACP,MAAM0C,EAAQ1C,EAAKyC,aACnB,OAAIvE,KAAKkH,SAELlH,KAAKoH,KAAKtF,EAAK8C,OAAO0C,KAAK,KAAMxF,EAAKD,UACtC7B,KAAKoH,KAAK,KACVpH,KAAK2H,SAASnD,GACdxE,KAAKoH,KAAK,KAKZpH,KAAKoH,KAAKpH,KAAKmH,UACfnH,KAAKoH,KAAKtF,EAAK8C,OAAO0C,KAAK,MAAOxF,EAAKD,UACvC7B,KAAKoH,KAAK,OAASpH,KAAKmH,OAAO,IAC/BnH,KAAK2H,SAASnD,EAAO,MACrBxE,KAAKoH,KAAKpH,KAAKmH,QAAQ,GAAK,KAAOnH,KAAKmH,SAAW,MAEvD,CAKAb,KAAKxE,GACH,GAAI9B,KAAKkH,SAAU,CACjB,MAAMb,EAAMvE,EAAKyE,UAAU7D,OAASZ,EAAKyE,UAAUe,KAAK,MAAQ,GAEhE,OACEtH,KAAKoH,KAAK,SAAWf,EAAKvE,EAAKD,UAC/B7B,KAAKoH,KAAK,KACVpH,KAAK2H,SAAS7F,EAAKyC,cACnBvE,KAAKoH,KAAK,I,CAGd,MAAMf,EAAMvE,EAAKyE,UAAU7D,OAASZ,EAAKyE,UAAUe,KAAK,MAAQ,IAAM,GAEtE,OACEtH,KAAKoH,KAAK,SAAWf,EAAKvE,EAAKD,UAC/B7B,KAAKoH,KAAK,OACVpH,KAAKoH,KAAKpH,KAAKmH,OAAO,IACtBnH,KAAK2H,SAAS7F,EAAKyC,aAAc,MACjCvE,KAAKoH,KAAKpH,KAAKmH,QAAQ,IACvBnH,KAAKoH,KAAK,MAEd,CAKAT,SAAS7E,GACP,OAAI9B,KAAKkH,SAELlH,KAAKoH,KAAK,aAActF,EAAKD,UAC7B7B,KAAKoH,KAAK,KACVpH,KAAK2H,SAAS7F,EAAKyC,cACnBvE,KAAKoH,KAAK,KAIZpH,KAAKoH,KAAK,cAAetF,EAAKD,UAC9B7B,KAAKoH,KAAK,OACVpH,KAAKoH,KAAKpH,KAAKmH,OAAO,IACtBnH,KAAK2H,SAAS7F,EAAKyC,aAAc,MACjCvE,KAAKoH,KAAKpH,KAAKmH,QAAQ,IACvBnH,KAAKoH,KAAK,MAEd,CAKAX,KAAK3E,GACH,OAAI9B,KAAKkH,SAELlH,KAAKoH,KAAK,QAAStF,EAAKD,UACxB7B,KAAKoH,KAAK,KACVpH,KAAK2H,SAAS7F,EAAKU,OACnBxC,KAAKoH,KAAK,KAIZpH,KAAKoH,KAAK,QAAStF,EAAKD,UACxB7B,KAAKoH,KAAK,OAASpH,KAAKmH,OAAO,IAC/BnH,KAAK2H,SAAS7F,EAAKU,MAAO,QAC1BxC,KAAKoH,KAAKpH,KAAKmH,QAAQ,GAAK,MAEhC,CAKArB,YAAYhE,GACV,OAAO9B,KAAKoH,KACV,iBAAmBtF,EAAKmD,KAAO,IAAMnD,EAAK6D,MAAQ,IAClD7D,EAAKD,SAET,CAKAgB,KAAKf,GACH,MAAM0C,EAAQ1C,EAAKyC,aACnB,IAAKC,EAAM9B,OACT,MAAO,GAGT,GAAI1C,KAAKkH,SACP,OACElH,KAAKoH,KAAKtF,EAAKyE,UAAUe,KAAK,KAAMxF,EAAKD,UACzC7B,KAAKoH,KAAK,KACVpH,KAAK2H,SAASnD,GACdxE,KAAKoH,KAAK,KAGd,MAAMD,EAASnH,KAAKmH,SAEpB,OACEnH,KAAKoH,KACHtF,EAAKyE,UACFxC,KAAIC,GACImD,EAASnD,IAEjBsD,KAAK,OACRxF,EAAKD,UAEP7B,KAAKoH,KAAK,QACVpH,KAAKoH,KAAKpH,KAAKmH,OAAO,IACtBnH,KAAK2H,SAASnD,EAAO,MACrBxE,KAAKoH,KAAKpH,KAAKmH,QAAQ,IACvBnH,KAAKoH,KAAK,KAAOpH,KAAKmH,SAAW,IAErC,CAKAlD,YAAYnC,GACV,OAAI9B,KAAKkH,SAELlH,KAAKoH,KAAKtF,EAAKwC,SAAW,IAAMxC,EAAKb,MAAOa,EAAKD,UACjD7B,KAAKoH,KAAK,KAIZpH,KAAKoH,KAAKpH,KAAKmH,UACfnH,KAAKoH,KAAKtF,EAAKwC,SAAW,KAAOxC,EAAKb,MAAOa,EAAKD,UAClD7B,KAAKoH,KAAK,IAEd,E,iECvYF,eAEA,UAAe,CACbtF,EACAF,IAEiB,IAAI,UAASA,GAAW,CAAC,GAC1BmG,QAAQjG,E,cCL1B,IAAY2B,E,oEAAAA,EAAA,EAAAA,WAAA,EAAAA,SAAQ,KAClB,wBACA,cACA,4BACA,oBACA,oBACA,sBACA,6BACA,uBACA,cACA,kBACA,wBACA,sBACA,gBACA,wBACA,cACA,qB,GClBEuE,EAA2B,CAAC,ECE5BC,EDCJ,SAASC,EAAoBC,GAE5B,IAAIC,EAAeJ,EAAyBG,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAaE,QAGrB,IAAIC,EAASP,EAAyBG,GAAY,CAGjDG,QAAS,CAAC,GAOX,OAHAE,EAAoBL,GAAUM,KAAKF,EAAOD,QAASC,EAAQA,EAAOD,QAASJ,GAGpEK,EAAOD,OACf,CCnB0BJ,CAAoB,K","sources":["webpack://@adobe/css-tools/./src/CssParseError.ts","webpack://@adobe/css-tools/./src/CssPosition.ts","webpack://@adobe/css-tools/./src/index.ts","webpack://@adobe/css-tools/./src/parse/index.ts","webpack://@adobe/css-tools/./src/stringify/compiler.ts","webpack://@adobe/css-tools/./src/stringify/index.ts","webpack://@adobe/css-tools/./src/type.ts","webpack://@adobe/css-tools/webpack/bootstrap","webpack://@adobe/css-tools/webpack/startup"],"sourcesContent":["export default class CssParseError extends Error {\n readonly reason: string;\n readonly filename?: string;\n readonly line: number;\n readonly column: number;\n readonly source: string;\n\n constructor(\n filename: string,\n msg: string,\n lineno: number,\n column: number,\n css: string\n ) {\n super(filename + ':' + lineno + ':' + column + ': ' + msg);\n this.reason = msg;\n this.filename = filename;\n this.line = lineno;\n this.column = column;\n this.source = css;\n }\n}\n","/**\n * Store position information for a node\n */\nexport default class Position {\n start: {line: number; column: number};\n end: {line: number; column: number};\n source?: string;\n\n constructor(\n start: {line: number; column: number},\n end: {line: number; column: number},\n source: string\n ) {\n this.start = start;\n this.end = end;\n this.source = source;\n }\n}\n","export {default as parse} from './parse';\nexport {default as stringify} from './stringify';\nexport * from './type';\nexport * from './CssParseError';\nexport * from './CssPosition';\n","import CssParseError from '../CssParseError';\nimport Position from '../CssPosition';\nimport {\n CssAtRuleAST,\n CssCharsetAST,\n CssCommentAST,\n CssCommonPositionAST,\n CssCustomMediaAST,\n CssDeclarationAST,\n CssDocumentAST,\n CssFontFaceAST,\n CssHostAST,\n CssImportAST,\n CssKeyframeAST,\n CssKeyframesAST,\n CssMediaAST,\n CssNamespaceAST,\n CssPageAST,\n CssRuleAST,\n CssStylesheetAST,\n CssSupportsAST,\n CssTypes,\n} from '../type';\n\n// http://www.w3.org/TR/CSS21/grammar.html\n// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\n\nexport const parse = (\n css: string,\n options?: {source?: string; silent?: boolean}\n): CssStylesheetAST => {\n options = options || {};\n\n /**\n * Positional.\n */\n let lineno = 1;\n let column = 1;\n\n /**\n * Update lineno and column based on `str`.\n */\n function updatePosition(str: string) {\n const lines = str.match(/\\n/g);\n if (lines) lineno += lines.length;\n const i = str.lastIndexOf('\\n');\n column = ~i ? str.length - i : column + str.length;\n }\n\n /**\n * Mark position and patch `node.position`.\n */\n function position() {\n const start = {line: lineno, column: column};\n return function (\n node: Omit\n ): T1 {\n (node as T1).position = new Position(\n start,\n {line: lineno, column: column},\n options?.source || ''\n );\n whitespace();\n return node as T1;\n };\n }\n\n /**\n * Error `msg`.\n */\n const errorsList: Array = [];\n\n function error(msg: string) {\n const err = new CssParseError(\n options?.source || '',\n msg,\n lineno,\n column,\n css\n );\n\n if (options?.silent) {\n errorsList.push(err);\n } else {\n throw err;\n }\n }\n\n /**\n * Parse stylesheet.\n */\n function stylesheet(): CssStylesheetAST {\n const rulesList = rules();\n\n const result: CssStylesheetAST = {\n type: CssTypes.stylesheet,\n stylesheet: {\n source: options?.source,\n rules: rulesList,\n parsingErrors: errorsList,\n },\n };\n\n return result;\n }\n\n /**\n * Opening brace.\n */\n function open() {\n return match(/^{\\s*/);\n }\n\n /**\n * Closing brace.\n */\n function close() {\n return match(/^}/);\n }\n\n /**\n * Parse ruleset.\n */\n function rules() {\n let node: CssRuleAST | CssAtRuleAST | void;\n const rules: Array = [];\n whitespace();\n comments(rules);\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\n if (node) {\n rules.push(node);\n comments(rules);\n }\n }\n return rules;\n }\n\n /**\n * Match `re` and return captures.\n */\n function match(re: RegExp) {\n const m = re.exec(css);\n if (!m) {\n return;\n }\n const str = m[0];\n updatePosition(str);\n css = css.slice(str.length);\n return m;\n }\n\n /**\n * Parse whitespace.\n */\n function whitespace() {\n match(/^\\s*/);\n }\n\n /**\n * Parse comments;\n */\n function comments(\n rules?: Array\n ) {\n let c;\n rules = rules || [];\n while ((c = comment())) {\n if (c) {\n rules.push(c);\n }\n }\n return rules;\n }\n\n /**\n * Parse comment.\n */\n function comment(): CssCommentAST | void {\n const pos = position();\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\n return;\n }\n\n const m = match(/^\\/\\*[^]*?\\*\\//);\n if (!m) {\n return error('End of comment missing');\n }\n\n return pos({\n type: CssTypes.comment,\n comment: m[0].slice(2, -2),\n });\n }\n\n /**\n * Parse selector.\n */\n function selector() {\n const m = match(/^([^{]+)/);\n if (!m) {\n return;\n }\n\n // remove comment in selector; [^] is equivalent to [.\\n\\r]\n const res = trim(m[0]).replace(/\\/\\*[^]*?\\*\\//gm, '');\n\n // Optimisation: If there is no ',' no need to split or post-process (this is less costly)\n if (res.indexOf(',') === -1) {\n return [res];\n }\n\n return (\n res\n /**\n * replace ',' by \\u200C for data selector (div[data-lang=\"fr,de,us\"])\n * replace ',' by \\u200C for nthChild and other selector (div:nth-child(2,3,4))\n *\n * Examples:\n * div[data-lang=\"fr,\\\"de,us\"]\n * div[data-lang='fr,\\'de,us']\n * div:matches(.toto, .titi:matches(.toto, .titi))\n *\n * Regex logic:\n * (\"|')(?:\\\\\\1|.)*?,(?:\\\\\\1|.)*?\\1 => Handle the \" and '\n * \\(.*?,.*?\\) => Handle the ()\n *\n * Optimization 0:\n * No greedy capture (see docs about the difference between .* and .*?)\n *\n * Optimization 1:\n * \\(.*?,.*?\\) instead of \\(.*?\\) to limit the number of replace (don't need to replace if , is not in the string)\n *\n * Optimization 2:\n * (\"|')(?:\\\\\\1|.)*?,(?:\\\\\\1|.)*?\\1 this use reference to capture group, it work faster.\n */\n .replace(/(\"|')(?:\\\\\\1|.)*?,(?:\\\\\\1|.)*?\\1|\\(.*?,.*?\\)/g, m =>\n m.replace(/,/g, '\\u200C')\n )\n // Split the selector by ','\n .split(',')\n // Replace back \\u200C by ','\n .map(s => {\n return trim(s.replace(/\\u200C/g, ','));\n })\n );\n }\n\n /**\n * Parse declaration.\n */\n function declaration(): CssDeclarationAST | void {\n const pos = position();\n\n // prop\n const propMatch = match(/^(\\*?[-#/*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\n if (!propMatch) {\n return;\n }\n const propValue = trim(propMatch[0]);\n\n // :\n if (!match(/^:\\s*/)) {\n return error(\"property missing ':'\");\n }\n\n // val\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^)]*?\\)|[^};])+)/);\n\n const ret = pos({\n type: CssTypes.declaration,\n property: propValue.replace(commentre, ''),\n value: val ? trim(val[0]).replace(commentre, '') : '',\n });\n\n // ;\n match(/^[;\\s]*/);\n\n return ret;\n }\n\n /**\n * Parse declarations.\n */\n function declarations() {\n const decls: Array = [];\n\n if (!open()) {\n return error(\"missing '{'\");\n }\n comments(decls);\n\n // declarations\n let decl;\n while ((decl = declaration())) {\n if (decl) {\n decls.push(decl);\n comments(decls);\n }\n }\n\n if (!close()) {\n return error(\"missing '}'\");\n }\n return decls;\n }\n\n /**\n * Parse keyframe.\n */\n function keyframe() {\n let m;\n const vals = [];\n const pos = position();\n\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\n vals.push(m[1]);\n match(/^,\\s*/);\n }\n\n if (!vals.length) {\n return;\n }\n\n return pos({\n type: CssTypes.keyframe,\n values: vals,\n declarations: declarations() || [],\n });\n }\n\n /**\n * Parse keyframes.\n */\n function atkeyframes(): CssKeyframesAST | void {\n const pos = position();\n const m1 = match(/^@([-\\w]+)?keyframes\\s*/);\n\n if (!m1) {\n return;\n }\n const vendor = m1[1];\n\n // identifier\n const m2 = match(/^([-\\w]+)\\s*/);\n if (!m2) {\n return error('@keyframes missing name');\n }\n const name = m2[1];\n\n if (!open()) {\n return error(\"@keyframes missing '{'\");\n }\n\n let frame;\n let frames: Array = comments();\n while ((frame = keyframe())) {\n frames.push(frame);\n frames = frames.concat(comments());\n }\n\n if (!close()) {\n return error(\"@keyframes missing '}'\");\n }\n\n return pos({\n type: CssTypes.keyframes,\n name: name,\n vendor: vendor,\n keyframes: frames,\n });\n }\n\n /**\n * Parse supports.\n */\n function atsupports(): CssSupportsAST | void {\n const pos = position();\n const m = match(/^@supports *([^{]+)/);\n\n if (!m) {\n return;\n }\n const supports = trim(m[1]);\n\n if (!open()) {\n return error(\"@supports missing '{'\");\n }\n\n const style = comments().concat(rules());\n\n if (!close()) {\n return error(\"@supports missing '}'\");\n }\n\n return pos({\n type: CssTypes.supports,\n supports: supports,\n rules: style,\n });\n }\n\n /**\n * Parse host.\n */\n function athost() {\n const pos = position();\n const m = match(/^@host\\s*/);\n\n if (!m) {\n return;\n }\n\n if (!open()) {\n return error(\"@host missing '{'\");\n }\n\n const style = comments().concat(rules());\n\n if (!close()) {\n return error(\"@host missing '}'\");\n }\n\n return pos({\n type: CssTypes.host,\n rules: style,\n });\n }\n\n /**\n * Parse media.\n */\n function atmedia(): CssMediaAST | void {\n const pos = position();\n const m = match(/^@media *([^{]+)/);\n\n if (!m) {\n return;\n }\n const media = trim(m[1]);\n\n if (!open()) {\n return error(\"@media missing '{'\");\n }\n\n const style = comments().concat(rules());\n\n if (!close()) {\n return error(\"@media missing '}'\");\n }\n\n return pos({\n type: CssTypes.media,\n media: media,\n rules: style,\n });\n }\n\n /**\n * Parse custom-media.\n */\n function atcustommedia(): CssCustomMediaAST | void {\n const pos = position();\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\n if (!m) {\n return;\n }\n\n return pos({\n type: CssTypes.customMedia,\n name: trim(m[1]),\n media: trim(m[2]),\n });\n }\n\n /**\n * Parse paged media.\n */\n function atpage(): CssPageAST | void {\n const pos = position();\n const m = match(/^@page */);\n if (!m) {\n return;\n }\n\n const sel = selector() || [];\n\n if (!open()) {\n return error(\"@page missing '{'\");\n }\n let decls = comments();\n\n // declarations\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n\n if (!close()) {\n return error(\"@page missing '}'\");\n }\n\n return pos({\n type: CssTypes.page,\n selectors: sel,\n declarations: decls,\n });\n }\n\n /**\n * Parse document.\n */\n function atdocument(): CssDocumentAST | void {\n const pos = position();\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\n if (!m) {\n return;\n }\n\n const vendor = trim(m[1]);\n const doc = trim(m[2]);\n\n if (!open()) {\n return error(\"@document missing '{'\");\n }\n\n const style = comments().concat(rules());\n\n if (!close()) {\n return error(\"@document missing '}'\");\n }\n\n return pos({\n type: CssTypes.document,\n document: doc,\n vendor: vendor,\n rules: style,\n });\n }\n\n /**\n * Parse font-face.\n */\n function atfontface(): CssFontFaceAST | void {\n const pos = position();\n const m = match(/^@font-face\\s*/);\n if (!m) {\n return;\n }\n\n if (!open()) {\n return error(\"@font-face missing '{'\");\n }\n let decls = comments();\n\n // declarations\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n\n if (!close()) {\n return error(\"@font-face missing '}'\");\n }\n\n return pos({\n type: CssTypes.fontFace,\n declarations: decls,\n });\n }\n\n /**\n * Parse import\n */\n const atimport = _compileAtrule('import');\n\n /**\n * Parse charset\n */\n const atcharset = _compileAtrule('charset');\n\n /**\n * Parse namespace\n */\n const atnamespace = _compileAtrule('namespace');\n\n /**\n * Parse non-block at-rules\n */\n function _compileAtrule(\n name: string\n ): () => T1 | void {\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\n return function (): T1 | void {\n const pos = position();\n const m = match(re);\n if (!m) {\n return;\n }\n const ret: Record = {type: name};\n ret[name] = m[1].trim();\n return pos(ret as unknown as T1) as T1;\n };\n }\n\n /**\n * Parse at rule.\n */\n function atrule(): CssAtRuleAST | void {\n if (css[0] !== '@') {\n return;\n }\n\n return (\n atkeyframes() ||\n atmedia() ||\n atcustommedia() ||\n atsupports() ||\n atimport() ||\n atcharset() ||\n atnamespace() ||\n atdocument() ||\n atpage() ||\n athost() ||\n atfontface()\n );\n }\n\n /**\n * Parse rule.\n */\n function rule() {\n const pos = position();\n const sel = selector();\n\n if (!sel) {\n return error('selector missing');\n }\n comments();\n\n return pos({\n type: CssTypes.rule,\n selectors: sel,\n declarations: declarations() || [],\n });\n }\n\n return addParent(stylesheet());\n};\n\n/**\n * Trim `str`.\n */\nfunction trim(str: string) {\n return str ? str.trim() : '';\n}\n\n/**\n * Adds non-enumerable parent node reference to each node.\n */\nfunction addParent(obj: T1, parent?: unknown): T1 {\n const isNode = obj && typeof obj.type === 'string';\n const childParent = isNode ? obj : parent;\n\n for (const k in obj) {\n const value = obj[k];\n if (Array.isArray(value)) {\n value.forEach(v => {\n addParent(v, childParent);\n });\n } else if (value && typeof value === 'object') {\n addParent(value, childParent);\n }\n }\n\n if (isNode) {\n Object.defineProperty(obj, 'parent', {\n configurable: true,\n writable: true,\n enumerable: false,\n value: parent || null,\n });\n }\n\n return obj;\n}\n\nexport default parse;\n","import {\n CssAllNodesAST,\n CssCharsetAST,\n CssCommentAST,\n CssCommonPositionAST,\n CssCustomMediaAST,\n CssDeclarationAST,\n CssDocumentAST,\n CssFontFaceAST,\n CssHostAST,\n CssImportAST,\n CssKeyframeAST,\n CssKeyframesAST,\n CssMediaAST,\n CssNamespaceAST,\n CssPageAST,\n CssRuleAST,\n CssStylesheetAST,\n CssSupportsAST,\n CssTypes,\n} from '../type';\n\nclass Compiler {\n level = 0;\n indentation = ' ';\n compress = false;\n\n constructor(options?: {indent?: string; compress?: boolean}) {\n if (typeof options?.indent === 'string') {\n this.indentation = options?.indent;\n }\n if (options?.compress) {\n this.compress = true;\n }\n }\n\n // We disable no-unused-vars for _position. We keep position for potential reintroduction of source-map\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n emit(str: string, _position?: CssCommonPositionAST['position']) {\n return str;\n }\n\n /**\n * Increase, decrease or return current indentation.\n */\n indent(level?: number) {\n this.level = this.level || 1;\n\n if (level) {\n this.level += level;\n return '';\n }\n\n return Array(this.level).join(this.indentation);\n }\n\n visit(node: CssAllNodesAST): string {\n switch (node.type) {\n case CssTypes.stylesheet:\n return this.stylesheet(node);\n case CssTypes.rule:\n return this.rule(node);\n case CssTypes.declaration:\n return this.declaration(node);\n case CssTypes.comment:\n return this.comment(node);\n case CssTypes.charset:\n return this.charset(node);\n case CssTypes.document:\n return this.document(node);\n case CssTypes.customMedia:\n return this.customMedia(node);\n case CssTypes.fontFace:\n return this.fontFace(node);\n case CssTypes.host:\n return this.host(node);\n case CssTypes.import:\n return this.import(node);\n case CssTypes.keyframes:\n return this.keyframes(node);\n case CssTypes.keyframe:\n return this.keyframe(node);\n case CssTypes.media:\n return this.media(node);\n case CssTypes.namespace:\n return this.namespace(node);\n case CssTypes.page:\n return this.page(node);\n case CssTypes.supports:\n return this.supports(node);\n }\n }\n\n mapVisit(nodes: Array, delim?: string) {\n let buf = '';\n delim = delim || '';\n\n for (let i = 0, length = nodes.length; i < length; i++) {\n buf += this.visit(nodes[i]);\n if (delim && i < length - 1) {\n buf += this.emit(delim);\n }\n }\n\n return buf;\n }\n\n compile(node: CssStylesheetAST) {\n if (this.compress) {\n return node.stylesheet.rules.map(this.visit, this).join('');\n }\n\n return this.stylesheet(node);\n }\n\n /**\n * Visit stylesheet node.\n */\n stylesheet(node: CssStylesheetAST) {\n return this.mapVisit(node.stylesheet.rules, '\\n\\n');\n }\n\n /**\n * Visit comment node.\n */\n comment(node: CssCommentAST) {\n if (this.compress) {\n return this.emit('', node.position);\n }\n return this.emit(this.indent() + '/*' + node.comment + '*/', node.position);\n }\n\n /**\n * Visit import node.\n */\n import(node: CssImportAST) {\n return this.emit('@import ' + node.import + ';', node.position);\n }\n\n /**\n * Visit media node.\n */\n media(node: CssMediaAST) {\n if (this.compress) {\n return (\n this.emit('@media ' + node.media, node.position) +\n this.emit('{') +\n this.mapVisit(node.rules) +\n this.emit('}')\n );\n }\n return (\n this.emit('@media ' + node.media, node.position) +\n this.emit(' {\\n' + this.indent(1)) +\n this.mapVisit(node.rules, '\\n\\n') +\n this.emit(this.indent(-1) + '\\n}')\n );\n }\n\n /**\n * Visit document node.\n */\n document(node: CssDocumentAST) {\n const doc = '@' + (node.vendor || '') + 'document ' + node.document;\n if (this.compress) {\n return (\n this.emit(doc, node.position) +\n this.emit('{') +\n this.mapVisit(node.rules) +\n this.emit('}')\n );\n }\n return (\n this.emit(doc, node.position) +\n this.emit(' ' + ' {\\n' + this.indent(1)) +\n this.mapVisit(node.rules, '\\n\\n') +\n this.emit(this.indent(-1) + '\\n}')\n );\n }\n\n /**\n * Visit charset node.\n */\n charset(node: CssCharsetAST) {\n return this.emit('@charset ' + node.charset + ';', node.position);\n }\n\n /**\n * Visit namespace node.\n */\n namespace(node: CssNamespaceAST) {\n return this.emit('@namespace ' + node.namespace + ';', node.position);\n }\n\n /**\n * Visit supports node.\n */\n supports(node: CssSupportsAST) {\n if (this.compress) {\n return (\n this.emit('@supports ' + node.supports, node.position) +\n this.emit('{') +\n this.mapVisit(node.rules) +\n this.emit('}')\n );\n }\n return (\n this.emit('@supports ' + node.supports, node.position) +\n this.emit(' {\\n' + this.indent(1)) +\n this.mapVisit(node.rules, '\\n\\n') +\n this.emit(this.indent(-1) + '\\n}')\n );\n }\n\n /**\n * Visit keyframes node.\n */\n keyframes(node: CssKeyframesAST) {\n if (this.compress) {\n return (\n this.emit(\n '@' + (node.vendor || '') + 'keyframes ' + node.name,\n node.position\n ) +\n this.emit('{') +\n this.mapVisit(node.keyframes) +\n this.emit('}')\n );\n }\n return (\n this.emit(\n '@' + (node.vendor || '') + 'keyframes ' + node.name,\n node.position\n ) +\n this.emit(' {\\n' + this.indent(1)) +\n this.mapVisit(node.keyframes, '\\n') +\n this.emit(this.indent(-1) + '}')\n );\n }\n\n /**\n * Visit keyframe node.\n */\n keyframe(node: CssKeyframeAST) {\n const decls = node.declarations;\n if (this.compress) {\n return (\n this.emit(node.values.join(','), node.position) +\n this.emit('{') +\n this.mapVisit(decls) +\n this.emit('}')\n );\n }\n\n return (\n this.emit(this.indent()) +\n this.emit(node.values.join(', '), node.position) +\n this.emit(' {\\n' + this.indent(1)) +\n this.mapVisit(decls, '\\n') +\n this.emit(this.indent(-1) + '\\n' + this.indent() + '}\\n')\n );\n }\n\n /**\n * Visit page node.\n */\n page(node: CssPageAST) {\n if (this.compress) {\n const sel = node.selectors.length ? node.selectors.join(', ') : '';\n\n return (\n this.emit('@page ' + sel, node.position) +\n this.emit('{') +\n this.mapVisit(node.declarations) +\n this.emit('}')\n );\n }\n const sel = node.selectors.length ? node.selectors.join(', ') + ' ' : '';\n\n return (\n this.emit('@page ' + sel, node.position) +\n this.emit('{\\n') +\n this.emit(this.indent(1)) +\n this.mapVisit(node.declarations, '\\n') +\n this.emit(this.indent(-1)) +\n this.emit('\\n}')\n );\n }\n\n /**\n * Visit font-face node.\n */\n fontFace(node: CssFontFaceAST) {\n if (this.compress) {\n return (\n this.emit('@font-face', node.position) +\n this.emit('{') +\n this.mapVisit(node.declarations) +\n this.emit('}')\n );\n }\n return (\n this.emit('@font-face ', node.position) +\n this.emit('{\\n') +\n this.emit(this.indent(1)) +\n this.mapVisit(node.declarations, '\\n') +\n this.emit(this.indent(-1)) +\n this.emit('\\n}')\n );\n }\n\n /**\n * Visit host node.\n */\n host(node: CssHostAST) {\n if (this.compress) {\n return (\n this.emit('@host', node.position) +\n this.emit('{') +\n this.mapVisit(node.rules) +\n this.emit('}')\n );\n }\n return (\n this.emit('@host', node.position) +\n this.emit(' {\\n' + this.indent(1)) +\n this.mapVisit(node.rules, '\\n\\n') +\n this.emit(this.indent(-1) + '\\n}')\n );\n }\n\n /**\n * Visit custom-media node.\n */\n customMedia(node: CssCustomMediaAST) {\n return this.emit(\n '@custom-media ' + node.name + ' ' + node.media + ';',\n node.position\n );\n }\n\n /**\n * Visit rule node.\n */\n rule(node: CssRuleAST) {\n const decls = node.declarations;\n if (!decls.length) {\n return '';\n }\n\n if (this.compress) {\n return (\n this.emit(node.selectors.join(','), node.position) +\n this.emit('{') +\n this.mapVisit(decls) +\n this.emit('}')\n );\n }\n const indent = this.indent();\n\n return (\n this.emit(\n node.selectors\n .map(s => {\n return indent + s;\n })\n .join(',\\n'),\n node.position\n ) +\n this.emit(' {\\n') +\n this.emit(this.indent(1)) +\n this.mapVisit(decls, '\\n') +\n this.emit(this.indent(-1)) +\n this.emit('\\n' + this.indent() + '}')\n );\n }\n\n /**\n * Visit declaration node.\n */\n declaration(node: CssDeclarationAST) {\n if (this.compress) {\n return (\n this.emit(node.property + ':' + node.value, node.position) +\n this.emit(';')\n );\n }\n return (\n this.emit(this.indent()) +\n this.emit(node.property + ': ' + node.value, node.position) +\n this.emit(';')\n );\n }\n}\n\nexport default Compiler;\n","import {CssStylesheetAST} from '../type';\nimport Compiler from './compiler';\n\nexport default (\n node: CssStylesheetAST,\n options?: ConstructorParameters[0]\n) => {\n const compiler = new Compiler(options || {});\n return compiler.compile(node);\n};\n","import CssParseError from './CssParseError';\nimport Position from './CssPosition';\n\nexport enum CssTypes {\n stylesheet = 'stylesheet',\n rule = 'rule',\n declaration = 'declaration',\n comment = 'comment',\n charset = 'charset',\n document = 'document',\n customMedia = 'custom-media',\n fontFace = 'font-face',\n host = 'host',\n import = 'import',\n keyframes = 'keyframes',\n keyframe = 'keyframe',\n media = 'media',\n namespace = 'namespace',\n page = 'page',\n supports = 'supports',\n}\n\nexport type CssCommonAST = {\n type: CssTypes;\n};\n\nexport type CssCommonPositionAST = CssCommonAST & {\n position?: Position;\n parent?: unknown;\n};\n\nexport type CssStylesheetAST = CssCommonAST & {\n type: CssTypes.stylesheet;\n stylesheet: {\n source?: string;\n rules: Array;\n parsingErrors?: Array;\n };\n};\n\nexport type CssRuleAST = CssCommonPositionAST & {\n type: CssTypes.rule;\n selectors: Array;\n declarations: Array;\n};\n\nexport type CssDeclarationAST = CssCommonPositionAST & {\n type: CssTypes.declaration;\n property: string;\n value: string;\n};\n\nexport type CssCommentAST = CssCommonPositionAST & {\n type: CssTypes.comment;\n comment: string;\n};\n\nexport type CssCharsetAST = CssCommonPositionAST & {\n type: CssTypes.charset;\n charset: string;\n};\nexport type CssCustomMediaAST = CssCommonPositionAST & {\n type: CssTypes.customMedia;\n name: string;\n media: string;\n};\nexport type CssDocumentAST = CssCommonPositionAST & {\n type: CssTypes.document;\n document: string;\n vendor?: string;\n rules: Array;\n};\nexport type CssFontFaceAST = CssCommonPositionAST & {\n type: CssTypes.fontFace;\n declarations: Array;\n};\nexport type CssHostAST = CssCommonPositionAST & {\n type: CssTypes.host;\n rules: Array;\n};\nexport type CssImportAST = CssCommonPositionAST & {\n type: CssTypes.import;\n import: string;\n};\nexport type CssKeyframesAST = CssCommonPositionAST & {\n type: CssTypes.keyframes;\n name: string;\n vendor?: string;\n keyframes: Array;\n};\nexport type CssKeyframeAST = CssCommonPositionAST & {\n type: CssTypes.keyframe;\n values: Array;\n declarations: Array;\n};\nexport type CssMediaAST = CssCommonPositionAST & {\n type: CssTypes.media;\n media: string;\n rules: Array;\n};\nexport type CssNamespaceAST = CssCommonPositionAST & {\n type: CssTypes.namespace;\n namespace: string;\n};\nexport type CssPageAST = CssCommonPositionAST & {\n type: CssTypes.page;\n selectors: Array;\n declarations: Array;\n};\nexport type CssSupportsAST = CssCommonPositionAST & {\n type: CssTypes.supports;\n supports: string;\n rules: Array;\n};\n\nexport type CssAtRuleAST =\n | CssRuleAST\n | CssCommentAST\n | CssCharsetAST\n | CssCustomMediaAST\n | CssDocumentAST\n | CssFontFaceAST\n | CssHostAST\n | CssImportAST\n | CssKeyframesAST\n | CssMediaAST\n | CssNamespaceAST\n | CssPageAST\n | CssSupportsAST;\n\nexport type CssAllNodesAST =\n | CssAtRuleAST\n | CssStylesheetAST\n | CssDeclarationAST\n | CssKeyframeAST;\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(607);\n"],"names":["CssParseError","Error","constructor","filename","msg","lineno","column","css","super","this","reason","line","source","start","end","default","commentre","trim","str","addParent","obj","parent","isNode","type","childParent","k","value","Array","isArray","forEach","v","Object","defineProperty","configurable","writable","enumerable","parse","options","position","node","whitespace","errorsList","error","err","silent","push","open","match","close","rules","comments","length","charAt","atrule","rule","re","m","exec","lines","i","lastIndexOf","updatePosition","slice","c","comment","pos","CssTypes","selector","res","replace","indexOf","split","map","s","declaration","propMatch","propValue","val","ret","property","declarations","decls","decl","keyframe","vals","values","atimport","_compileAtrule","atcharset","atnamespace","name","RegExp","m1","vendor","m2","frame","frames","concat","keyframes","atkeyframes","media","style","atmedia","customMedia","atcustommedia","supports","atsupports","doc","document","atdocument","sel","page","selectors","atpage","host","athost","fontFace","atfontface","rulesList","stylesheet","parsingErrors","level","indentation","compress","indent","emit","_position","join","visit","charset","import","namespace","mapVisit","nodes","delim","buf","compile","__webpack_module_cache__","__webpack_exports__","__webpack_require__","moduleId","cachedModule","undefined","exports","module","__webpack_modules__","call"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/@adobe/css-tools/dist/cjs/index.d.ts b/node_modules/@adobe/css-tools/dist/cjs/index.d.ts new file mode 100644 index 0000000..d26123c --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/index.d.ts @@ -0,0 +1,5 @@ +export { default as parse } from './parse'; +export { default as stringify } from './stringify'; +export * from './type'; +export * from './CssParseError'; +export * from './CssPosition'; diff --git a/node_modules/@adobe/css-tools/dist/cjs/parse/index.d.ts b/node_modules/@adobe/css-tools/dist/cjs/parse/index.d.ts new file mode 100644 index 0000000..d329626 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/parse/index.d.ts @@ -0,0 +1,6 @@ +import { CssStylesheetAST } from '../type'; +export declare const parse: (css: string, options?: { + source?: string; + silent?: boolean; +}) => CssStylesheetAST; +export default parse; diff --git a/node_modules/@adobe/css-tools/dist/cjs/stringify/compiler.d.ts b/node_modules/@adobe/css-tools/dist/cjs/stringify/compiler.d.ts new file mode 100644 index 0000000..462e89c --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/stringify/compiler.d.ts @@ -0,0 +1,83 @@ +import { CssAllNodesAST, CssCharsetAST, CssCommentAST, CssCommonPositionAST, CssCustomMediaAST, CssDeclarationAST, CssDocumentAST, CssFontFaceAST, CssHostAST, CssImportAST, CssKeyframeAST, CssKeyframesAST, CssMediaAST, CssNamespaceAST, CssPageAST, CssRuleAST, CssStylesheetAST, CssSupportsAST } from '../type'; +declare class Compiler { + level: number; + indentation: string; + compress: boolean; + constructor(options?: { + indent?: string; + compress?: boolean; + }); + emit(str: string, _position?: CssCommonPositionAST['position']): string; + /** + * Increase, decrease or return current indentation. + */ + indent(level?: number): string; + visit(node: CssAllNodesAST): string; + mapVisit(nodes: Array, delim?: string): string; + compile(node: CssStylesheetAST): string; + /** + * Visit stylesheet node. + */ + stylesheet(node: CssStylesheetAST): string; + /** + * Visit comment node. + */ + comment(node: CssCommentAST): string; + /** + * Visit import node. + */ + import(node: CssImportAST): string; + /** + * Visit media node. + */ + media(node: CssMediaAST): string; + /** + * Visit document node. + */ + document(node: CssDocumentAST): string; + /** + * Visit charset node. + */ + charset(node: CssCharsetAST): string; + /** + * Visit namespace node. + */ + namespace(node: CssNamespaceAST): string; + /** + * Visit supports node. + */ + supports(node: CssSupportsAST): string; + /** + * Visit keyframes node. + */ + keyframes(node: CssKeyframesAST): string; + /** + * Visit keyframe node. + */ + keyframe(node: CssKeyframeAST): string; + /** + * Visit page node. + */ + page(node: CssPageAST): string; + /** + * Visit font-face node. + */ + fontFace(node: CssFontFaceAST): string; + /** + * Visit host node. + */ + host(node: CssHostAST): string; + /** + * Visit custom-media node. + */ + customMedia(node: CssCustomMediaAST): string; + /** + * Visit rule node. + */ + rule(node: CssRuleAST): string; + /** + * Visit declaration node. + */ + declaration(node: CssDeclarationAST): string; +} +export default Compiler; diff --git a/node_modules/@adobe/css-tools/dist/cjs/stringify/index.d.ts b/node_modules/@adobe/css-tools/dist/cjs/stringify/index.d.ts new file mode 100644 index 0000000..c493a9c --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/stringify/index.d.ts @@ -0,0 +1,4 @@ +import { CssStylesheetAST } from '../type'; +import Compiler from './compiler'; +declare const _default: (node: CssStylesheetAST, options?: ConstructorParameters[0]) => string; +export default _default; diff --git a/node_modules/@adobe/css-tools/dist/cjs/type.d.ts b/node_modules/@adobe/css-tools/dist/cjs/type.d.ts new file mode 100644 index 0000000..36da8e3 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/cjs/type.d.ts @@ -0,0 +1,108 @@ +import CssParseError from './CssParseError'; +import Position from './CssPosition'; +export declare enum CssTypes { + stylesheet = "stylesheet", + rule = "rule", + declaration = "declaration", + comment = "comment", + charset = "charset", + document = "document", + customMedia = "custom-media", + fontFace = "font-face", + host = "host", + import = "import", + keyframes = "keyframes", + keyframe = "keyframe", + media = "media", + namespace = "namespace", + page = "page", + supports = "supports" +} +export declare type CssCommonAST = { + type: CssTypes; +}; +export declare type CssCommonPositionAST = CssCommonAST & { + position?: Position; + parent?: unknown; +}; +export declare type CssStylesheetAST = CssCommonAST & { + type: CssTypes.stylesheet; + stylesheet: { + source?: string; + rules: Array; + parsingErrors?: Array; + }; +}; +export declare type CssRuleAST = CssCommonPositionAST & { + type: CssTypes.rule; + selectors: Array; + declarations: Array; +}; +export declare type CssDeclarationAST = CssCommonPositionAST & { + type: CssTypes.declaration; + property: string; + value: string; +}; +export declare type CssCommentAST = CssCommonPositionAST & { + type: CssTypes.comment; + comment: string; +}; +export declare type CssCharsetAST = CssCommonPositionAST & { + type: CssTypes.charset; + charset: string; +}; +export declare type CssCustomMediaAST = CssCommonPositionAST & { + type: CssTypes.customMedia; + name: string; + media: string; +}; +export declare type CssDocumentAST = CssCommonPositionAST & { + type: CssTypes.document; + document: string; + vendor?: string; + rules: Array; +}; +export declare type CssFontFaceAST = CssCommonPositionAST & { + type: CssTypes.fontFace; + declarations: Array; +}; +export declare type CssHostAST = CssCommonPositionAST & { + type: CssTypes.host; + rules: Array; +}; +export declare type CssImportAST = CssCommonPositionAST & { + type: CssTypes.import; + import: string; +}; +export declare type CssKeyframesAST = CssCommonPositionAST & { + type: CssTypes.keyframes; + name: string; + vendor?: string; + keyframes: Array; +}; +export declare type CssKeyframeAST = CssCommonPositionAST & { + type: CssTypes.keyframe; + values: Array; + declarations: Array; +}; +export declare type CssMediaAST = CssCommonPositionAST & { + type: CssTypes.media; + media: string; + rules: Array; +}; +export declare type CssNamespaceAST = CssCommonPositionAST & { + type: CssTypes.namespace; + namespace: string; +}; +export declare type CssPageAST = CssCommonPositionAST & { + type: CssTypes.page; + selectors: Array; + declarations: Array; +}; +export declare type CssSupportsAST = CssCommonPositionAST & { + type: CssTypes.supports; + supports: string; + rules: Array; +}; +export declare type CssAtRuleAST = CssRuleAST | CssCommentAST | CssCharsetAST | CssCustomMediaAST | CssDocumentAST | CssFontFaceAST | CssHostAST | CssImportAST | CssKeyframesAST | CssMediaAST | CssNamespaceAST | CssPageAST | CssSupportsAST; +export declare type CssAllNodesAST = CssAtRuleAST | CssStylesheetAST | CssDeclarationAST | CssKeyframeAST; diff --git a/node_modules/@adobe/css-tools/dist/umd/cssTools.js b/node_modules/@adobe/css-tools/dist/umd/cssTools.js new file mode 100644 index 0000000..e0e5320 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/umd/cssTools.js @@ -0,0 +1,2 @@ +!function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var s=e();for(var i in s)("object"==typeof exports?exports:t)[i]=s[i]}}(this,(()=>(()=>{"use strict";var t={831:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});class s extends Error{constructor(t,e,s,i,n){super(t+":"+s+":"+i+": "+e),this.reason=e,this.filename=t,this.line=s,this.column=i,this.source=n}}e.default=s},711:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class{constructor(t,e,s){this.start=t,this.end=e,this.source=s}}},607:function(t,e,s){var i=this&&this.__createBinding||(Object.create?function(t,e,s,i){void 0===i&&(i=s);var n=Object.getOwnPropertyDescriptor(e,s);n&&!("get"in n?!e.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return e[s]}}),Object.defineProperty(t,i,n)}:function(t,e,s,i){void 0===i&&(i=s),t[i]=e[s]}),n=this&&this.__exportStar||function(t,e){for(var s in t)"default"===s||Object.prototype.hasOwnProperty.call(e,s)||i(e,t,s)};Object.defineProperty(e,"__esModule",{value:!0}),e.stringify=e.parse=void 0;var r=s(654);Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return r.default}});var o=s(373);Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return o.default}}),n(s(371),e),n(s(831),e),n(s(711),e)},654:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parse=void 0;const i=s(831),n=s(711),r=s(371),o=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;function c(t){return t?t.trim():""}function u(t,e){const s=t&&"string"==typeof t.type,i=s?t:e;for(const e in t){const s=t[e];Array.isArray(s)?s.forEach((t=>{u(t,i)})):s&&"object"==typeof s&&u(s,i)}return s&&Object.defineProperty(t,"parent",{configurable:!0,writable:!0,enumerable:!1,value:e||null}),t}e.parse=(t,e)=>{e=e||{};let s=1,a=1;function m(){const t={line:s,column:a};return function(i){return i.position=new n.default(t,{line:s,column:a},(null==e?void 0:e.source)||""),g(),i}}const p=[];function h(n){const r=new i.default((null==e?void 0:e.source)||"",n,s,a,t);if(!(null==e?void 0:e.silent))throw r;p.push(r)}function l(){return y(/^{\s*/)}function f(){return y(/^}/)}function d(){let e;const s=[];for(g(),v(s);t.length&&"}"!==t.charAt(0)&&(e=w()||M());)e&&(s.push(e),v(s));return s}function y(e){const i=e.exec(t);if(!i)return;const n=i[0];return function(t){const e=t.match(/\n/g);e&&(s+=e.length);const i=t.lastIndexOf("\n");a=~i?t.length-i:a+t.length}(n),t=t.slice(n.length),i}function g(){y(/^\s*/)}function v(t){let e;for(t=t||[];e=C();)e&&t.push(e);return t}function C(){const e=m();if("/"!==t.charAt(0)||"*"!==t.charAt(1))return;const s=y(/^\/\*[^]*?\*\//);return s?e({type:r.CssTypes.comment,comment:s[0].slice(2,-2)}):h("End of comment missing")}function T(){const t=y(/^([^{]+)/);if(!t)return;const e=c(t[0]).replace(/\/\*[^]*?\*\//gm,"");return-1===e.indexOf(",")?[e]:e.replace(/("|')(?:\\\1|.)*?,(?:\\\1|.)*?\1|\(.*?,.*?\)/g,(t=>t.replace(/,/g,"‌"))).split(",").map((t=>c(t.replace(/\u200C/g,","))))}function b(){const t=m(),e=y(/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);if(!e)return;const s=c(e[0]);if(!y(/^:\s*/))return h("property missing ':'");const i=y(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/),n=t({type:r.CssTypes.declaration,property:s.replace(o,""),value:i?c(i[0]).replace(o,""):""});return y(/^[;\s]*/),n}function j(){const t=[];if(!l())return h("missing '{'");let e;for(v(t);e=b();)e&&(t.push(e),v(t));return f()?t:h("missing '}'")}function k(){let t;const e=[],s=m();for(;t=y(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/);)e.push(t[1]),y(/^,\s*/);if(e.length)return s({type:r.CssTypes.keyframe,values:e,declarations:j()||[]})}const _=x("import"),V=x("charset"),O=x("namespace");function x(t){const e=new RegExp("^@"+t+"\\s*([^;]+);");return function(){const s=m(),i=y(e);if(!i)return;const n={type:t};return n[t]=i[1].trim(),s(n)}}function w(){if("@"===t[0])return function(){const t=m(),e=y(/^@([-\w]+)?keyframes\s*/);if(!e)return;const s=e[1],i=y(/^([-\w]+)\s*/);if(!i)return h("@keyframes missing name");const n=i[1];if(!l())return h("@keyframes missing '{'");let o,c=v();for(;o=k();)c.push(o),c=c.concat(v());return f()?t({type:r.CssTypes.keyframes,name:n,vendor:s,keyframes:c}):h("@keyframes missing '}'")}()||function(){const t=m(),e=y(/^@media *([^{]+)/);if(!e)return;const s=c(e[1]);if(!l())return h("@media missing '{'");const i=v().concat(d());return f()?t({type:r.CssTypes.media,media:s,rules:i}):h("@media missing '}'")}()||function(){const t=m(),e=y(/^@custom-media\s+(--[^\s]+)\s*([^{;]+);/);if(e)return t({type:r.CssTypes.customMedia,name:c(e[1]),media:c(e[2])})}()||function(){const t=m(),e=y(/^@supports *([^{]+)/);if(!e)return;const s=c(e[1]);if(!l())return h("@supports missing '{'");const i=v().concat(d());return f()?t({type:r.CssTypes.supports,supports:s,rules:i}):h("@supports missing '}'")}()||_()||V()||O()||function(){const t=m(),e=y(/^@([-\w]+)?document *([^{]+)/);if(!e)return;const s=c(e[1]),i=c(e[2]);if(!l())return h("@document missing '{'");const n=v().concat(d());return f()?t({type:r.CssTypes.document,document:i,vendor:s,rules:n}):h("@document missing '}'")}()||function(){const t=m();if(!y(/^@page */))return;const e=T()||[];if(!l())return h("@page missing '{'");let s,i=v();for(;s=b();)i.push(s),i=i.concat(v());return f()?t({type:r.CssTypes.page,selectors:e,declarations:i}):h("@page missing '}'")}()||function(){const t=m();if(!y(/^@host\s*/))return;if(!l())return h("@host missing '{'");const e=v().concat(d());return f()?t({type:r.CssTypes.host,rules:e}):h("@host missing '}'")}()||function(){const t=m();if(!y(/^@font-face\s*/))return;if(!l())return h("@font-face missing '{'");let e,s=v();for(;e=b();)s.push(e),s=s.concat(v());return f()?t({type:r.CssTypes.fontFace,declarations:s}):h("@font-face missing '}'")}()}function M(){const t=m(),e=T();return e?(v(),t({type:r.CssTypes.rule,selectors:e,declarations:j()||[]})):h("selector missing")}return u(function(){const t=d();return{type:r.CssTypes.stylesheet,stylesheet:{source:null==e?void 0:e.source,rules:t,parsingErrors:p}}}())},e.default=e.parse},854:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});const i=s(371);e.default=class{constructor(t){this.level=0,this.indentation=" ",this.compress=!1,"string"==typeof(null==t?void 0:t.indent)&&(this.indentation=null==t?void 0:t.indent),(null==t?void 0:t.compress)&&(this.compress=!0)}emit(t,e){return t}indent(t){return this.level=this.level||1,t?(this.level+=t,""):Array(this.level).join(this.indentation)}visit(t){switch(t.type){case i.CssTypes.stylesheet:return this.stylesheet(t);case i.CssTypes.rule:return this.rule(t);case i.CssTypes.declaration:return this.declaration(t);case i.CssTypes.comment:return this.comment(t);case i.CssTypes.charset:return this.charset(t);case i.CssTypes.document:return this.document(t);case i.CssTypes.customMedia:return this.customMedia(t);case i.CssTypes.fontFace:return this.fontFace(t);case i.CssTypes.host:return this.host(t);case i.CssTypes.import:return this.import(t);case i.CssTypes.keyframes:return this.keyframes(t);case i.CssTypes.keyframe:return this.keyframe(t);case i.CssTypes.media:return this.media(t);case i.CssTypes.namespace:return this.namespace(t);case i.CssTypes.page:return this.page(t);case i.CssTypes.supports:return this.supports(t)}}mapVisit(t,e){let s="";e=e||"";for(let i=0,n=t.length;is+t)).join(",\n"),t.position)+this.emit(" {\n")+this.emit(this.indent(1))+this.mapVisit(e,"\n")+this.emit(this.indent(-1))+this.emit("\n"+this.indent()+"}")}declaration(t){return this.compress?this.emit(t.property+":"+t.value,t.position)+this.emit(";"):this.emit(this.indent())+this.emit(t.property+": "+t.value,t.position)+this.emit(";")}}},373:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});const i=s(854);e.default=(t,e)=>new i.default(e||{}).compile(t)},371:(t,e)=>{var s;Object.defineProperty(e,"__esModule",{value:!0}),e.CssTypes=void 0,(s=e.CssTypes||(e.CssTypes={})).stylesheet="stylesheet",s.rule="rule",s.declaration="declaration",s.comment="comment",s.charset="charset",s.document="document",s.customMedia="custom-media",s.fontFace="font-face",s.host="host",s.import="import",s.keyframes="keyframes",s.keyframe="keyframe",s.media="media",s.namespace="namespace",s.page="page",s.supports="supports"}},e={};return function s(i){var n=e[i];if(void 0!==n)return n.exports;var r=e[i]={exports:{}};return t[i].call(r.exports,r,r.exports,s),r.exports}(607)})())); +//# sourceMappingURL=cssTools.js.map \ No newline at end of file diff --git a/node_modules/@adobe/css-tools/dist/umd/cssTools.js.map b/node_modules/@adobe/css-tools/dist/umd/cssTools.js.map new file mode 100644 index 0000000..3e33321 --- /dev/null +++ b/node_modules/@adobe/css-tools/dist/umd/cssTools.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cssTools.js","mappings":"CAAA,SAA2CA,EAAMC,GAChD,GAAsB,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,SACb,GAAqB,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,OACP,CACJ,IAAIK,EAAIL,IACR,IAAI,IAAIM,KAAKD,GAAuB,iBAAZJ,QAAuBA,QAAUF,GAAMO,GAAKD,EAAEC,EACvE,CACA,CATD,CASGC,MAAM,I,uFCTT,MAAqBC,UAAsBC,MAOzCC,YACEC,EACAC,EACAC,EACAC,EACAC,GAEAC,MAAML,EAAW,IAAME,EAAS,IAAMC,EAAS,KAAOF,GACtDL,KAAKU,OAASL,EACdL,KAAKI,SAAWA,EAChBJ,KAAKW,KAAOL,EACZN,KAAKO,OAASA,EACdP,KAAKY,OAASJ,CAChB,EApBF,W,+DCGA,gBAKEL,YACEU,EACAC,EACAF,GAEAZ,KAAKa,MAAQA,EACbb,KAAKc,IAAMA,EACXd,KAAKY,OAASA,CAChB,E,shBChBF,aAAQ,uEAAAG,OAAO,IACf,aAAQ,2EAAAA,OAAO,IACf,YACA,YACA,W,gFCJA,eACA,SACA,SAwBMC,EAAY,kCAqnBlB,SAASC,EAAKC,GACZ,OAAOA,EAAMA,EAAID,OAAS,EAC5B,CAKA,SAASE,EAAsCC,EAASC,GACtD,MAAMC,EAASF,GAA2B,iBAAbA,EAAIG,KAC3BC,EAAcF,EAASF,EAAMC,EAEnC,IAAK,MAAMI,KAAKL,EAAK,CACnB,MAAMM,EAAQN,EAAIK,GACdE,MAAMC,QAAQF,GAChBA,EAAMG,SAAQC,IACZX,EAAUW,EAAGN,EAAY,IAElBE,GAA0B,iBAAVA,GACzBP,EAAUO,EAAOF,E,CAarB,OATIF,GACFS,OAAOC,eAAeZ,EAAK,SAAU,CACnCa,cAAc,EACdC,UAAU,EACVC,YAAY,EACZT,MAAOL,GAAU,OAIdD,CACT,CAnpBa,EAAAgB,MAAQ,CACnB5B,EACA6B,KAEAA,EAAUA,GAAW,CAAC,EAKtB,IAAI/B,EAAS,EACTC,EAAS,EAeb,SAAS+B,IACP,MAAMzB,EAAQ,CAACF,KAAML,EAAQC,OAAQA,GACrC,OAAO,SACLgC,GAQA,OANCA,EAAYD,SAAW,IAAI,UAC1BzB,EACA,CAACF,KAAML,EAAQC,OAAQA,IACvB8B,aAAO,EAAPA,EAASzB,SAAU,IAErB4B,IACOD,CACT,CACF,CAKA,MAAME,EAAmC,GAEzC,SAASC,EAAMrC,GACb,MAAMsC,EAAM,IAAI,WACdN,aAAO,EAAPA,EAASzB,SAAU,GACnBP,EACAC,EACAC,EACAC,GAGF,KAAI6B,aAAO,EAAPA,EAASO,QAGX,MAAMD,EAFNF,EAAWI,KAAKF,EAIpB,CAuBA,SAASG,IACP,OAAOC,EAAM,QACf,CAKA,SAASC,IACP,OAAOD,EAAM,KACf,CAKA,SAASE,IACP,IAAIV,EACJ,MAAMU,EAA0C,GAGhD,IAFAT,IACAU,EAASD,GACFzC,EAAI2C,QAA4B,MAAlB3C,EAAI4C,OAAO,KAAeb,EAAOc,KAAYC,MAC5Df,IACFU,EAAMJ,KAAKN,GACXW,EAASD,IAGb,OAAOA,CACT,CAKA,SAASF,EAAMQ,GACb,MAAMC,EAAID,EAAGE,KAAKjD,GAClB,IAAKgD,EACH,OAEF,MAAMtC,EAAMsC,EAAE,GAGd,OA1GF,SAAwBtC,GACtB,MAAMwC,EAAQxC,EAAI6B,MAAM,OACpBW,IAAOpD,GAAUoD,EAAMP,QAC3B,MAAMpD,EAAImB,EAAIyC,YAAY,MAC1BpD,GAAUR,EAAImB,EAAIiC,OAASpD,EAAIQ,EAASW,EAAIiC,MAC9C,CAmGES,CAAe1C,GACfV,EAAMA,EAAIqD,MAAM3C,EAAIiC,QACbK,CACT,CAKA,SAAShB,IACPO,EAAM,OACR,CAKA,SAASG,EACPD,GAEA,IAAIa,EAEJ,IADAb,EAAQA,GAAS,GACTa,EAAIC,KACND,GACFb,EAAMJ,KAAKiB,GAGf,OAAOb,CACT,CAKA,SAASc,IACP,MAAMC,EAAM1B,IACZ,GAAI,MAAQ9B,EAAI4C,OAAO,IAAM,MAAQ5C,EAAI4C,OAAO,GAC9C,OAGF,MAAMI,EAAIT,EAAM,kBAChB,OAAKS,EAIEQ,EAAmB,CACxBzC,KAAM,EAAA0C,SAASF,QACfA,QAASP,EAAE,GAAGK,MAAM,GAAI,KALjBnB,EAAM,yBAOjB,CAKA,SAASwB,IACP,MAAMV,EAAIT,EAAM,YAChB,IAAKS,EACH,OAIF,MAAMW,EAAMlD,EAAKuC,EAAE,IAAIY,QAAQ,kBAAmB,IAGlD,OAA0B,IAAtBD,EAAIE,QAAQ,KACP,CAACF,GAIRA,EAuBGC,QAAQ,iDAAiDZ,GACxDA,EAAEY,QAAQ,KAAM,OAGjBE,MAAM,KAENC,KAAIC,GACIvD,EAAKuD,EAAEJ,QAAQ,UAAW,OAGzC,CAKA,SAASK,IACP,MAAMT,EAAM1B,IAGNoC,EAAY3B,EAAM,0CACxB,IAAK2B,EACH,OAEF,MAAMC,EAAY1D,EAAKyD,EAAU,IAGjC,IAAK3B,EAAM,SACT,OAAOL,EAAM,wBAIf,MAAMkC,EAAM7B,EAAM,wDAEZ8B,EAAMb,EAAuB,CACjCzC,KAAM,EAAA0C,SAASQ,YACfK,SAAUH,EAAUP,QAAQpD,EAAW,IACvCU,MAAOkD,EAAM3D,EAAK2D,EAAI,IAAIR,QAAQpD,EAAW,IAAM,KAMrD,OAFA+B,EAAM,WAEC8B,CACT,CAKA,SAASE,IACP,MAAMC,EAAkD,GAExD,IAAKlC,IACH,OAAOJ,EAAM,eAKf,IAAIuC,EACJ,IAJA/B,EAAS8B,GAIDC,EAAOR,KACTQ,IACFD,EAAMnC,KAAKoC,GACX/B,EAAS8B,IAIb,OAAKhC,IAGEgC,EAFEtC,EAAM,cAGjB,CAKA,SAASwC,IACP,IAAI1B,EACJ,MAAM2B,EAAO,GACPnB,EAAM1B,IAEZ,KAAQkB,EAAIT,EAAM,wCAChBoC,EAAKtC,KAAKW,EAAE,IACZT,EAAM,SAGR,GAAKoC,EAAKhC,OAIV,OAAOa,EAAoB,CACzBzC,KAAM,EAAA0C,SAASiB,SACfE,OAAQD,EACRJ,aAAcA,KAAkB,IAEpC,CAuPA,MAAMM,EAAWC,EAA6B,UAKxCC,EAAYD,EAA8B,WAK1CE,EAAcF,EAAgC,aAKpD,SAASA,EACPG,GAEA,MAAMlC,EAAK,IAAImC,OAAO,KAAOD,EAAO,gBACpC,OAAO,WACL,MAAMzB,EAAM1B,IACNkB,EAAIT,EAAMQ,GAChB,IAAKC,EACH,OAEF,MAAMqB,EAA8B,CAACtD,KAAMkE,GAE3C,OADAZ,EAAIY,GAAQjC,EAAE,GAAGvC,OACV+C,EAAQa,EACjB,CACF,CAKA,SAASxB,IACP,GAAe,MAAX7C,EAAI,GAIR,OAzRF,WACE,MAAMwD,EAAM1B,IACNqD,EAAK5C,EAAM,2BAEjB,IAAK4C,EACH,OAEF,MAAMC,EAASD,EAAG,GAGZE,EAAK9C,EAAM,gBACjB,IAAK8C,EACH,OAAOnD,EAAM,2BAEf,MAAM+C,EAAOI,EAAG,GAEhB,IAAK/C,IACH,OAAOJ,EAAM,0BAGf,IAAIoD,EACAC,EAAgD7C,IACpD,KAAQ4C,EAAQZ,KACda,EAAOlD,KAAKiD,GACZC,EAASA,EAAOC,OAAO9C,KAGzB,OAAKF,IAIEgB,EAAqB,CAC1BzC,KAAM,EAAA0C,SAASgC,UACfR,KAAMA,EACNG,OAAQA,EACRK,UAAWF,IAPJrD,EAAM,yBASjB,CAqPIwD,IAxLJ,WACE,MAAMlC,EAAM1B,IACNkB,EAAIT,EAAM,oBAEhB,IAAKS,EACH,OAEF,MAAM2C,EAAQlF,EAAKuC,EAAE,IAErB,IAAKV,IACH,OAAOJ,EAAM,sBAGf,MAAM0D,EAAQlD,IAAyB8C,OAAO/C,KAE9C,OAAKD,IAIEgB,EAAiB,CACtBzC,KAAM,EAAA0C,SAASkC,MACfA,MAAOA,EACPlD,MAAOmD,IANA1D,EAAM,qBAQjB,CAiKI2D,IA5JJ,WACE,MAAMrC,EAAM1B,IACNkB,EAAIT,EAAM,2CAChB,GAAKS,EAIL,OAAOQ,EAAuB,CAC5BzC,KAAM,EAAA0C,SAASqC,YACfb,KAAMxE,EAAKuC,EAAE,IACb2C,MAAOlF,EAAKuC,EAAE,KAElB,CAiJI+C,IAlPJ,WACE,MAAMvC,EAAM1B,IACNkB,EAAIT,EAAM,uBAEhB,IAAKS,EACH,OAEF,MAAMgD,EAAWvF,EAAKuC,EAAE,IAExB,IAAKV,IACH,OAAOJ,EAAM,yBAGf,MAAM0D,EAAQlD,IAAyB8C,OAAO/C,KAE9C,OAAKD,IAIEgB,EAAoB,CACzBzC,KAAM,EAAA0C,SAASuC,SACfA,SAAUA,EACVvD,MAAOmD,IANA1D,EAAM,wBAQjB,CA2NI+D,IACApB,KACAE,KACAC,KA7GJ,WACE,MAAMxB,EAAM1B,IACNkB,EAAIT,EAAM,gCAChB,IAAKS,EACH,OAGF,MAAMoC,EAAS3E,EAAKuC,EAAE,IAChBkD,EAAMzF,EAAKuC,EAAE,IAEnB,IAAKV,IACH,OAAOJ,EAAM,yBAGf,MAAM0D,EAAQlD,IAAyB8C,OAAO/C,KAE9C,OAAKD,IAIEgB,EAAoB,CACzBzC,KAAM,EAAA0C,SAAS0C,SACfA,SAAUD,EACVd,OAAQA,EACR3C,MAAOmD,IAPA1D,EAAM,wBASjB,CAoFIkE,IAjJJ,WACE,MAAM5C,EAAM1B,IAEZ,IADUS,EAAM,YAEd,OAGF,MAAM8D,EAAM3C,KAAc,GAE1B,IAAKpB,IACH,OAAOJ,EAAM,qBAEf,IAGIuC,EAHAD,EAAQ9B,IAIZ,KAAQ+B,EAAOR,KACbO,EAAMnC,KAAKoC,GACXD,EAAQA,EAAMgB,OAAO9C,KAGvB,OAAKF,IAIEgB,EAAgB,CACrBzC,KAAM,EAAA0C,SAAS6C,KACfC,UAAWF,EACX9B,aAAcC,IANPtC,EAAM,oBAQjB,CAoHIsE,IA3NJ,WACE,MAAMhD,EAAM1B,IAGZ,IAFUS,EAAM,aAGd,OAGF,IAAKD,IACH,OAAOJ,EAAM,qBAGf,MAAM0D,EAAQlD,IAAyB8C,OAAO/C,KAE9C,OAAKD,IAIEgB,EAAgB,CACrBzC,KAAM,EAAA0C,SAASgD,KACfhE,MAAOmD,IALA1D,EAAM,oBAOjB,CAsMIwE,IAjFJ,WACE,MAAMlD,EAAM1B,IAEZ,IADUS,EAAM,kBAEd,OAGF,IAAKD,IACH,OAAOJ,EAAM,0BAEf,IAGIuC,EAHAD,EAAQ9B,IAIZ,KAAQ+B,EAAOR,KACbO,EAAMnC,KAAKoC,GACXD,EAAQA,EAAMgB,OAAO9C,KAGvB,OAAKF,IAIEgB,EAAoB,CACzBzC,KAAM,EAAA0C,SAASkD,SACfpC,aAAcC,IALPtC,EAAM,yBAOjB,CAuDI0E,EAEJ,CAKA,SAAS9D,IACP,MAAMU,EAAM1B,IACNuE,EAAM3C,IAEZ,OAAK2C,GAGL3D,IAEOc,EAAgB,CACrBzC,KAAM,EAAA0C,SAASX,KACfyD,UAAWF,EACX9B,aAAcA,KAAkB,MAPzBrC,EAAM,mBASjB,CAEA,OAAOvB,EA7iBP,WACE,MAAMkG,EAAYpE,IAWlB,MATiC,CAC/B1B,KAAM,EAAA0C,SAASqD,WACfA,WAAY,CACV1G,OAAQyB,aAAO,EAAPA,EAASzB,OACjBqC,MAAOoE,EACPE,cAAe9E,GAKrB,CAgiBiB6E,GAAa,EAwChC,UAAe,EAAAlF,K,iECjrBf,eA2YA,UArXA,MAKEjC,YAAYkC,GAJZ,KAAAmF,MAAQ,EACR,KAAAC,YAAc,KACd,KAAAC,UAAW,EAGsB,iBAApBrF,aAAO,EAAPA,EAASsF,UAClB3H,KAAKyH,YAAcpF,aAAO,EAAPA,EAASsF,SAE1BtF,aAAO,EAAPA,EAASqF,YACX1H,KAAK0H,UAAW,EAEpB,CAIAE,KAAK1G,EAAa2G,GAChB,OAAO3G,CACT,CAKAyG,OAAOH,GAGL,OAFAxH,KAAKwH,MAAQxH,KAAKwH,OAAS,EAEvBA,GACFxH,KAAKwH,OAASA,EACP,IAGF7F,MAAM3B,KAAKwH,OAAOM,KAAK9H,KAAKyH,YACrC,CAEAM,MAAMxF,GACJ,OAAQA,EAAKhB,MACX,KAAK,EAAA0C,SAASqD,WACZ,OAAOtH,KAAKsH,WAAW/E,GACzB,KAAK,EAAA0B,SAASX,KACZ,OAAOtD,KAAKsD,KAAKf,GACnB,KAAK,EAAA0B,SAASQ,YACZ,OAAOzE,KAAKyE,YAAYlC,GAC1B,KAAK,EAAA0B,SAASF,QACZ,OAAO/D,KAAK+D,QAAQxB,GACtB,KAAK,EAAA0B,SAAS+D,QACZ,OAAOhI,KAAKgI,QAAQzF,GACtB,KAAK,EAAA0B,SAAS0C,SACZ,OAAO3G,KAAK2G,SAASpE,GACvB,KAAK,EAAA0B,SAASqC,YACZ,OAAOtG,KAAKsG,YAAY/D,GAC1B,KAAK,EAAA0B,SAASkD,SACZ,OAAOnH,KAAKmH,SAAS5E,GACvB,KAAK,EAAA0B,SAASgD,KACZ,OAAOjH,KAAKiH,KAAK1E,GACnB,KAAK,EAAA0B,SAASgE,OACZ,OAAOjI,KAAKiI,OAAO1F,GACrB,KAAK,EAAA0B,SAASgC,UACZ,OAAOjG,KAAKiG,UAAU1D,GACxB,KAAK,EAAA0B,SAASiB,SACZ,OAAOlF,KAAKkF,SAAS3C,GACvB,KAAK,EAAA0B,SAASkC,MACZ,OAAOnG,KAAKmG,MAAM5D,GACpB,KAAK,EAAA0B,SAASiE,UACZ,OAAOlI,KAAKkI,UAAU3F,GACxB,KAAK,EAAA0B,SAAS6C,KACZ,OAAO9G,KAAK8G,KAAKvE,GACnB,KAAK,EAAA0B,SAASuC,SACZ,OAAOxG,KAAKwG,SAASjE,GAE3B,CAEA4F,SAASC,EAA8BC,GACrC,IAAIC,EAAM,GACVD,EAAQA,GAAS,GAEjB,IAAK,IAAItI,EAAI,EAAGoD,EAASiF,EAAMjF,OAAQpD,EAAIoD,EAAQpD,IACjDuI,GAAOtI,KAAK+H,MAAMK,EAAMrI,IACpBsI,GAAStI,EAAIoD,EAAS,IACxBmF,GAAOtI,KAAK4H,KAAKS,IAIrB,OAAOC,CACT,CAEAC,QAAQhG,GACN,OAAIvC,KAAK0H,SACAnF,EAAK+E,WAAWrE,MAAMsB,IAAIvE,KAAK+H,MAAO/H,MAAM8H,KAAK,IAGnD9H,KAAKsH,WAAW/E,EACzB,CAKA+E,WAAW/E,GACT,OAAOvC,KAAKmI,SAAS5F,EAAK+E,WAAWrE,MAAO,OAC9C,CAKAc,QAAQxB,GACN,OAAIvC,KAAK0H,SACA1H,KAAK4H,KAAK,GAAIrF,EAAKD,UAErBtC,KAAK4H,KAAK5H,KAAK2H,SAAW,KAAOpF,EAAKwB,QAAU,KAAMxB,EAAKD,SACpE,CAKA2F,OAAO1F,GACL,OAAOvC,KAAK4H,KAAK,WAAarF,EAAK0F,OAAS,IAAK1F,EAAKD,SACxD,CAKA6D,MAAM5D,GACJ,OAAIvC,KAAK0H,SAEL1H,KAAK4H,KAAK,UAAYrF,EAAK4D,MAAO5D,EAAKD,UACvCtC,KAAK4H,KAAK,KACV5H,KAAKmI,SAAS5F,EAAKU,OACnBjD,KAAK4H,KAAK,KAIZ5H,KAAK4H,KAAK,UAAYrF,EAAK4D,MAAO5D,EAAKD,UACvCtC,KAAK4H,KAAK,OAAS5H,KAAK2H,OAAO,IAC/B3H,KAAKmI,SAAS5F,EAAKU,MAAO,QAC1BjD,KAAK4H,KAAK5H,KAAK2H,QAAQ,GAAK,MAEhC,CAKAhB,SAASpE,GACP,MAAMmE,EAAM,KAAOnE,EAAKqD,QAAU,IAAM,YAAcrD,EAAKoE,SAC3D,OAAI3G,KAAK0H,SAEL1H,KAAK4H,KAAKlB,EAAKnE,EAAKD,UACpBtC,KAAK4H,KAAK,KACV5H,KAAKmI,SAAS5F,EAAKU,OACnBjD,KAAK4H,KAAK,KAIZ5H,KAAK4H,KAAKlB,EAAKnE,EAAKD,UACpBtC,KAAK4H,KAAK,QAAe5H,KAAK2H,OAAO,IACrC3H,KAAKmI,SAAS5F,EAAKU,MAAO,QAC1BjD,KAAK4H,KAAK5H,KAAK2H,QAAQ,GAAK,MAEhC,CAKAK,QAAQzF,GACN,OAAOvC,KAAK4H,KAAK,YAAcrF,EAAKyF,QAAU,IAAKzF,EAAKD,SAC1D,CAKA4F,UAAU3F,GACR,OAAOvC,KAAK4H,KAAK,cAAgBrF,EAAK2F,UAAY,IAAK3F,EAAKD,SAC9D,CAKAkE,SAASjE,GACP,OAAIvC,KAAK0H,SAEL1H,KAAK4H,KAAK,aAAerF,EAAKiE,SAAUjE,EAAKD,UAC7CtC,KAAK4H,KAAK,KACV5H,KAAKmI,SAAS5F,EAAKU,OACnBjD,KAAK4H,KAAK,KAIZ5H,KAAK4H,KAAK,aAAerF,EAAKiE,SAAUjE,EAAKD,UAC7CtC,KAAK4H,KAAK,OAAS5H,KAAK2H,OAAO,IAC/B3H,KAAKmI,SAAS5F,EAAKU,MAAO,QAC1BjD,KAAK4H,KAAK5H,KAAK2H,QAAQ,GAAK,MAEhC,CAKA1B,UAAU1D,GACR,OAAIvC,KAAK0H,SAEL1H,KAAK4H,KACH,KAAOrF,EAAKqD,QAAU,IAAM,aAAerD,EAAKkD,KAChDlD,EAAKD,UAEPtC,KAAK4H,KAAK,KACV5H,KAAKmI,SAAS5F,EAAK0D,WACnBjG,KAAK4H,KAAK,KAIZ5H,KAAK4H,KACH,KAAOrF,EAAKqD,QAAU,IAAM,aAAerD,EAAKkD,KAChDlD,EAAKD,UAEPtC,KAAK4H,KAAK,OAAS5H,KAAK2H,OAAO,IAC/B3H,KAAKmI,SAAS5F,EAAK0D,UAAW,MAC9BjG,KAAK4H,KAAK5H,KAAK2H,QAAQ,GAAK,IAEhC,CAKAzC,SAAS3C,GACP,MAAMyC,EAAQzC,EAAKwC,aACnB,OAAI/E,KAAK0H,SAEL1H,KAAK4H,KAAKrF,EAAK6C,OAAO0C,KAAK,KAAMvF,EAAKD,UACtCtC,KAAK4H,KAAK,KACV5H,KAAKmI,SAASnD,GACdhF,KAAK4H,KAAK,KAKZ5H,KAAK4H,KAAK5H,KAAK2H,UACf3H,KAAK4H,KAAKrF,EAAK6C,OAAO0C,KAAK,MAAOvF,EAAKD,UACvCtC,KAAK4H,KAAK,OAAS5H,KAAK2H,OAAO,IAC/B3H,KAAKmI,SAASnD,EAAO,MACrBhF,KAAK4H,KAAK5H,KAAK2H,QAAQ,GAAK,KAAO3H,KAAK2H,SAAW,MAEvD,CAKAb,KAAKvE,GACH,GAAIvC,KAAK0H,SAAU,CACjB,MAAMb,EAAMtE,EAAKwE,UAAU5D,OAASZ,EAAKwE,UAAUe,KAAK,MAAQ,GAEhE,OACE9H,KAAK4H,KAAK,SAAWf,EAAKtE,EAAKD,UAC/BtC,KAAK4H,KAAK,KACV5H,KAAKmI,SAAS5F,EAAKwC,cACnB/E,KAAK4H,KAAK,I,CAGd,MAAMf,EAAMtE,EAAKwE,UAAU5D,OAASZ,EAAKwE,UAAUe,KAAK,MAAQ,IAAM,GAEtE,OACE9H,KAAK4H,KAAK,SAAWf,EAAKtE,EAAKD,UAC/BtC,KAAK4H,KAAK,OACV5H,KAAK4H,KAAK5H,KAAK2H,OAAO,IACtB3H,KAAKmI,SAAS5F,EAAKwC,aAAc,MACjC/E,KAAK4H,KAAK5H,KAAK2H,QAAQ,IACvB3H,KAAK4H,KAAK,MAEd,CAKAT,SAAS5E,GACP,OAAIvC,KAAK0H,SAEL1H,KAAK4H,KAAK,aAAcrF,EAAKD,UAC7BtC,KAAK4H,KAAK,KACV5H,KAAKmI,SAAS5F,EAAKwC,cACnB/E,KAAK4H,KAAK,KAIZ5H,KAAK4H,KAAK,cAAerF,EAAKD,UAC9BtC,KAAK4H,KAAK,OACV5H,KAAK4H,KAAK5H,KAAK2H,OAAO,IACtB3H,KAAKmI,SAAS5F,EAAKwC,aAAc,MACjC/E,KAAK4H,KAAK5H,KAAK2H,QAAQ,IACvB3H,KAAK4H,KAAK,MAEd,CAKAX,KAAK1E,GACH,OAAIvC,KAAK0H,SAEL1H,KAAK4H,KAAK,QAASrF,EAAKD,UACxBtC,KAAK4H,KAAK,KACV5H,KAAKmI,SAAS5F,EAAKU,OACnBjD,KAAK4H,KAAK,KAIZ5H,KAAK4H,KAAK,QAASrF,EAAKD,UACxBtC,KAAK4H,KAAK,OAAS5H,KAAK2H,OAAO,IAC/B3H,KAAKmI,SAAS5F,EAAKU,MAAO,QAC1BjD,KAAK4H,KAAK5H,KAAK2H,QAAQ,GAAK,MAEhC,CAKArB,YAAY/D,GACV,OAAOvC,KAAK4H,KACV,iBAAmBrF,EAAKkD,KAAO,IAAMlD,EAAK4D,MAAQ,IAClD5D,EAAKD,SAET,CAKAgB,KAAKf,GACH,MAAMyC,EAAQzC,EAAKwC,aACnB,IAAKC,EAAM7B,OACT,MAAO,GAGT,GAAInD,KAAK0H,SACP,OACE1H,KAAK4H,KAAKrF,EAAKwE,UAAUe,KAAK,KAAMvF,EAAKD,UACzCtC,KAAK4H,KAAK,KACV5H,KAAKmI,SAASnD,GACdhF,KAAK4H,KAAK,KAGd,MAAMD,EAAS3H,KAAK2H,SAEpB,OACE3H,KAAK4H,KACHrF,EAAKwE,UACFxC,KAAIC,GACImD,EAASnD,IAEjBsD,KAAK,OACRvF,EAAKD,UAEPtC,KAAK4H,KAAK,QACV5H,KAAK4H,KAAK5H,KAAK2H,OAAO,IACtB3H,KAAKmI,SAASnD,EAAO,MACrBhF,KAAK4H,KAAK5H,KAAK2H,QAAQ,IACvB3H,KAAK4H,KAAK,KAAO5H,KAAK2H,SAAW,IAErC,CAKAlD,YAAYlC,GACV,OAAIvC,KAAK0H,SAEL1H,KAAK4H,KAAKrF,EAAKuC,SAAW,IAAMvC,EAAKb,MAAOa,EAAKD,UACjDtC,KAAK4H,KAAK,KAIZ5H,KAAK4H,KAAK5H,KAAK2H,UACf3H,KAAK4H,KAAKrF,EAAKuC,SAAW,KAAOvC,EAAKb,MAAOa,EAAKD,UAClDtC,KAAK4H,KAAK,IAEd,E,iECvYF,eAEA,UAAe,CACbrF,EACAF,IAEiB,IAAI,UAASA,GAAW,CAAC,GAC1BkG,QAAQhG,E,cCL1B,IAAY0B,E,oEAAAA,EAAA,EAAAA,WAAA,EAAAA,SAAQ,KAClB,wBACA,cACA,4BACA,oBACA,oBACA,sBACA,6BACA,uBACA,cACA,kBACA,wBACA,sBACA,gBACA,wBACA,cACA,qB,GClBEuE,EAA2B,CAAC,E,OAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAajJ,QAGrB,IAAIC,EAAS6I,EAAyBE,GAAY,CAGjDhJ,QAAS,CAAC,GAOX,OAHAmJ,EAAoBH,GAAUI,KAAKnJ,EAAOD,QAASC,EAAQA,EAAOD,QAAS+I,GAGpE9I,EAAOD,OACf,CCnB0B+I,CAAoB,I","sources":["webpack://@adobe/css-tools/webpack/universalModuleDefinition","webpack://@adobe/css-tools/./src/CssParseError.ts","webpack://@adobe/css-tools/./src/CssPosition.ts","webpack://@adobe/css-tools/./src/index.ts","webpack://@adobe/css-tools/./src/parse/index.ts","webpack://@adobe/css-tools/./src/stringify/compiler.ts","webpack://@adobe/css-tools/./src/stringify/index.ts","webpack://@adobe/css-tools/./src/type.ts","webpack://@adobe/css-tools/webpack/bootstrap","webpack://@adobe/css-tools/webpack/startup"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, () => {\nreturn ","export default class CssParseError extends Error {\n readonly reason: string;\n readonly filename?: string;\n readonly line: number;\n readonly column: number;\n readonly source: string;\n\n constructor(\n filename: string,\n msg: string,\n lineno: number,\n column: number,\n css: string\n ) {\n super(filename + ':' + lineno + ':' + column + ': ' + msg);\n this.reason = msg;\n this.filename = filename;\n this.line = lineno;\n this.column = column;\n this.source = css;\n }\n}\n","/**\n * Store position information for a node\n */\nexport default class Position {\n start: {line: number; column: number};\n end: {line: number; column: number};\n source?: string;\n\n constructor(\n start: {line: number; column: number},\n end: {line: number; column: number},\n source: string\n ) {\n this.start = start;\n this.end = end;\n this.source = source;\n }\n}\n","export {default as parse} from './parse';\nexport {default as stringify} from './stringify';\nexport * from './type';\nexport * from './CssParseError';\nexport * from './CssPosition';\n","import CssParseError from '../CssParseError';\nimport Position from '../CssPosition';\nimport {\n CssAtRuleAST,\n CssCharsetAST,\n CssCommentAST,\n CssCommonPositionAST,\n CssCustomMediaAST,\n CssDeclarationAST,\n CssDocumentAST,\n CssFontFaceAST,\n CssHostAST,\n CssImportAST,\n CssKeyframeAST,\n CssKeyframesAST,\n CssMediaAST,\n CssNamespaceAST,\n CssPageAST,\n CssRuleAST,\n CssStylesheetAST,\n CssSupportsAST,\n CssTypes,\n} from '../type';\n\n// http://www.w3.org/TR/CSS21/grammar.html\n// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\n\nexport const parse = (\n css: string,\n options?: {source?: string; silent?: boolean}\n): CssStylesheetAST => {\n options = options || {};\n\n /**\n * Positional.\n */\n let lineno = 1;\n let column = 1;\n\n /**\n * Update lineno and column based on `str`.\n */\n function updatePosition(str: string) {\n const lines = str.match(/\\n/g);\n if (lines) lineno += lines.length;\n const i = str.lastIndexOf('\\n');\n column = ~i ? str.length - i : column + str.length;\n }\n\n /**\n * Mark position and patch `node.position`.\n */\n function position() {\n const start = {line: lineno, column: column};\n return function (\n node: Omit\n ): T1 {\n (node as T1).position = new Position(\n start,\n {line: lineno, column: column},\n options?.source || ''\n );\n whitespace();\n return node as T1;\n };\n }\n\n /**\n * Error `msg`.\n */\n const errorsList: Array = [];\n\n function error(msg: string) {\n const err = new CssParseError(\n options?.source || '',\n msg,\n lineno,\n column,\n css\n );\n\n if (options?.silent) {\n errorsList.push(err);\n } else {\n throw err;\n }\n }\n\n /**\n * Parse stylesheet.\n */\n function stylesheet(): CssStylesheetAST {\n const rulesList = rules();\n\n const result: CssStylesheetAST = {\n type: CssTypes.stylesheet,\n stylesheet: {\n source: options?.source,\n rules: rulesList,\n parsingErrors: errorsList,\n },\n };\n\n return result;\n }\n\n /**\n * Opening brace.\n */\n function open() {\n return match(/^{\\s*/);\n }\n\n /**\n * Closing brace.\n */\n function close() {\n return match(/^}/);\n }\n\n /**\n * Parse ruleset.\n */\n function rules() {\n let node: CssRuleAST | CssAtRuleAST | void;\n const rules: Array = [];\n whitespace();\n comments(rules);\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\n if (node) {\n rules.push(node);\n comments(rules);\n }\n }\n return rules;\n }\n\n /**\n * Match `re` and return captures.\n */\n function match(re: RegExp) {\n const m = re.exec(css);\n if (!m) {\n return;\n }\n const str = m[0];\n updatePosition(str);\n css = css.slice(str.length);\n return m;\n }\n\n /**\n * Parse whitespace.\n */\n function whitespace() {\n match(/^\\s*/);\n }\n\n /**\n * Parse comments;\n */\n function comments(\n rules?: Array\n ) {\n let c;\n rules = rules || [];\n while ((c = comment())) {\n if (c) {\n rules.push(c);\n }\n }\n return rules;\n }\n\n /**\n * Parse comment.\n */\n function comment(): CssCommentAST | void {\n const pos = position();\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\n return;\n }\n\n const m = match(/^\\/\\*[^]*?\\*\\//);\n if (!m) {\n return error('End of comment missing');\n }\n\n return pos({\n type: CssTypes.comment,\n comment: m[0].slice(2, -2),\n });\n }\n\n /**\n * Parse selector.\n */\n function selector() {\n const m = match(/^([^{]+)/);\n if (!m) {\n return;\n }\n\n // remove comment in selector; [^] is equivalent to [.\\n\\r]\n const res = trim(m[0]).replace(/\\/\\*[^]*?\\*\\//gm, '');\n\n // Optimisation: If there is no ',' no need to split or post-process (this is less costly)\n if (res.indexOf(',') === -1) {\n return [res];\n }\n\n return (\n res\n /**\n * replace ',' by \\u200C for data selector (div[data-lang=\"fr,de,us\"])\n * replace ',' by \\u200C for nthChild and other selector (div:nth-child(2,3,4))\n *\n * Examples:\n * div[data-lang=\"fr,\\\"de,us\"]\n * div[data-lang='fr,\\'de,us']\n * div:matches(.toto, .titi:matches(.toto, .titi))\n *\n * Regex logic:\n * (\"|')(?:\\\\\\1|.)*?,(?:\\\\\\1|.)*?\\1 => Handle the \" and '\n * \\(.*?,.*?\\) => Handle the ()\n *\n * Optimization 0:\n * No greedy capture (see docs about the difference between .* and .*?)\n *\n * Optimization 1:\n * \\(.*?,.*?\\) instead of \\(.*?\\) to limit the number of replace (don't need to replace if , is not in the string)\n *\n * Optimization 2:\n * (\"|')(?:\\\\\\1|.)*?,(?:\\\\\\1|.)*?\\1 this use reference to capture group, it work faster.\n */\n .replace(/(\"|')(?:\\\\\\1|.)*?,(?:\\\\\\1|.)*?\\1|\\(.*?,.*?\\)/g, m =>\n m.replace(/,/g, '\\u200C')\n )\n // Split the selector by ','\n .split(',')\n // Replace back \\u200C by ','\n .map(s => {\n return trim(s.replace(/\\u200C/g, ','));\n })\n );\n }\n\n /**\n * Parse declaration.\n */\n function declaration(): CssDeclarationAST | void {\n const pos = position();\n\n // prop\n const propMatch = match(/^(\\*?[-#/*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\n if (!propMatch) {\n return;\n }\n const propValue = trim(propMatch[0]);\n\n // :\n if (!match(/^:\\s*/)) {\n return error(\"property missing ':'\");\n }\n\n // val\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^)]*?\\)|[^};])+)/);\n\n const ret = pos({\n type: CssTypes.declaration,\n property: propValue.replace(commentre, ''),\n value: val ? trim(val[0]).replace(commentre, '') : '',\n });\n\n // ;\n match(/^[;\\s]*/);\n\n return ret;\n }\n\n /**\n * Parse declarations.\n */\n function declarations() {\n const decls: Array = [];\n\n if (!open()) {\n return error(\"missing '{'\");\n }\n comments(decls);\n\n // declarations\n let decl;\n while ((decl = declaration())) {\n if (decl) {\n decls.push(decl);\n comments(decls);\n }\n }\n\n if (!close()) {\n return error(\"missing '}'\");\n }\n return decls;\n }\n\n /**\n * Parse keyframe.\n */\n function keyframe() {\n let m;\n const vals = [];\n const pos = position();\n\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\n vals.push(m[1]);\n match(/^,\\s*/);\n }\n\n if (!vals.length) {\n return;\n }\n\n return pos({\n type: CssTypes.keyframe,\n values: vals,\n declarations: declarations() || [],\n });\n }\n\n /**\n * Parse keyframes.\n */\n function atkeyframes(): CssKeyframesAST | void {\n const pos = position();\n const m1 = match(/^@([-\\w]+)?keyframes\\s*/);\n\n if (!m1) {\n return;\n }\n const vendor = m1[1];\n\n // identifier\n const m2 = match(/^([-\\w]+)\\s*/);\n if (!m2) {\n return error('@keyframes missing name');\n }\n const name = m2[1];\n\n if (!open()) {\n return error(\"@keyframes missing '{'\");\n }\n\n let frame;\n let frames: Array = comments();\n while ((frame = keyframe())) {\n frames.push(frame);\n frames = frames.concat(comments());\n }\n\n if (!close()) {\n return error(\"@keyframes missing '}'\");\n }\n\n return pos({\n type: CssTypes.keyframes,\n name: name,\n vendor: vendor,\n keyframes: frames,\n });\n }\n\n /**\n * Parse supports.\n */\n function atsupports(): CssSupportsAST | void {\n const pos = position();\n const m = match(/^@supports *([^{]+)/);\n\n if (!m) {\n return;\n }\n const supports = trim(m[1]);\n\n if (!open()) {\n return error(\"@supports missing '{'\");\n }\n\n const style = comments().concat(rules());\n\n if (!close()) {\n return error(\"@supports missing '}'\");\n }\n\n return pos({\n type: CssTypes.supports,\n supports: supports,\n rules: style,\n });\n }\n\n /**\n * Parse host.\n */\n function athost() {\n const pos = position();\n const m = match(/^@host\\s*/);\n\n if (!m) {\n return;\n }\n\n if (!open()) {\n return error(\"@host missing '{'\");\n }\n\n const style = comments().concat(rules());\n\n if (!close()) {\n return error(\"@host missing '}'\");\n }\n\n return pos({\n type: CssTypes.host,\n rules: style,\n });\n }\n\n /**\n * Parse media.\n */\n function atmedia(): CssMediaAST | void {\n const pos = position();\n const m = match(/^@media *([^{]+)/);\n\n if (!m) {\n return;\n }\n const media = trim(m[1]);\n\n if (!open()) {\n return error(\"@media missing '{'\");\n }\n\n const style = comments().concat(rules());\n\n if (!close()) {\n return error(\"@media missing '}'\");\n }\n\n return pos({\n type: CssTypes.media,\n media: media,\n rules: style,\n });\n }\n\n /**\n * Parse custom-media.\n */\n function atcustommedia(): CssCustomMediaAST | void {\n const pos = position();\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\n if (!m) {\n return;\n }\n\n return pos({\n type: CssTypes.customMedia,\n name: trim(m[1]),\n media: trim(m[2]),\n });\n }\n\n /**\n * Parse paged media.\n */\n function atpage(): CssPageAST | void {\n const pos = position();\n const m = match(/^@page */);\n if (!m) {\n return;\n }\n\n const sel = selector() || [];\n\n if (!open()) {\n return error(\"@page missing '{'\");\n }\n let decls = comments();\n\n // declarations\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n\n if (!close()) {\n return error(\"@page missing '}'\");\n }\n\n return pos({\n type: CssTypes.page,\n selectors: sel,\n declarations: decls,\n });\n }\n\n /**\n * Parse document.\n */\n function atdocument(): CssDocumentAST | void {\n const pos = position();\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\n if (!m) {\n return;\n }\n\n const vendor = trim(m[1]);\n const doc = trim(m[2]);\n\n if (!open()) {\n return error(\"@document missing '{'\");\n }\n\n const style = comments().concat(rules());\n\n if (!close()) {\n return error(\"@document missing '}'\");\n }\n\n return pos({\n type: CssTypes.document,\n document: doc,\n vendor: vendor,\n rules: style,\n });\n }\n\n /**\n * Parse font-face.\n */\n function atfontface(): CssFontFaceAST | void {\n const pos = position();\n const m = match(/^@font-face\\s*/);\n if (!m) {\n return;\n }\n\n if (!open()) {\n return error(\"@font-face missing '{'\");\n }\n let decls = comments();\n\n // declarations\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n\n if (!close()) {\n return error(\"@font-face missing '}'\");\n }\n\n return pos({\n type: CssTypes.fontFace,\n declarations: decls,\n });\n }\n\n /**\n * Parse import\n */\n const atimport = _compileAtrule('import');\n\n /**\n * Parse charset\n */\n const atcharset = _compileAtrule('charset');\n\n /**\n * Parse namespace\n */\n const atnamespace = _compileAtrule('namespace');\n\n /**\n * Parse non-block at-rules\n */\n function _compileAtrule(\n name: string\n ): () => T1 | void {\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\n return function (): T1 | void {\n const pos = position();\n const m = match(re);\n if (!m) {\n return;\n }\n const ret: Record = {type: name};\n ret[name] = m[1].trim();\n return pos(ret as unknown as T1) as T1;\n };\n }\n\n /**\n * Parse at rule.\n */\n function atrule(): CssAtRuleAST | void {\n if (css[0] !== '@') {\n return;\n }\n\n return (\n atkeyframes() ||\n atmedia() ||\n atcustommedia() ||\n atsupports() ||\n atimport() ||\n atcharset() ||\n atnamespace() ||\n atdocument() ||\n atpage() ||\n athost() ||\n atfontface()\n );\n }\n\n /**\n * Parse rule.\n */\n function rule() {\n const pos = position();\n const sel = selector();\n\n if (!sel) {\n return error('selector missing');\n }\n comments();\n\n return pos({\n type: CssTypes.rule,\n selectors: sel,\n declarations: declarations() || [],\n });\n }\n\n return addParent(stylesheet());\n};\n\n/**\n * Trim `str`.\n */\nfunction trim(str: string) {\n return str ? str.trim() : '';\n}\n\n/**\n * Adds non-enumerable parent node reference to each node.\n */\nfunction addParent(obj: T1, parent?: unknown): T1 {\n const isNode = obj && typeof obj.type === 'string';\n const childParent = isNode ? obj : parent;\n\n for (const k in obj) {\n const value = obj[k];\n if (Array.isArray(value)) {\n value.forEach(v => {\n addParent(v, childParent);\n });\n } else if (value && typeof value === 'object') {\n addParent(value, childParent);\n }\n }\n\n if (isNode) {\n Object.defineProperty(obj, 'parent', {\n configurable: true,\n writable: true,\n enumerable: false,\n value: parent || null,\n });\n }\n\n return obj;\n}\n\nexport default parse;\n","import {\n CssAllNodesAST,\n CssCharsetAST,\n CssCommentAST,\n CssCommonPositionAST,\n CssCustomMediaAST,\n CssDeclarationAST,\n CssDocumentAST,\n CssFontFaceAST,\n CssHostAST,\n CssImportAST,\n CssKeyframeAST,\n CssKeyframesAST,\n CssMediaAST,\n CssNamespaceAST,\n CssPageAST,\n CssRuleAST,\n CssStylesheetAST,\n CssSupportsAST,\n CssTypes,\n} from '../type';\n\nclass Compiler {\n level = 0;\n indentation = ' ';\n compress = false;\n\n constructor(options?: {indent?: string; compress?: boolean}) {\n if (typeof options?.indent === 'string') {\n this.indentation = options?.indent;\n }\n if (options?.compress) {\n this.compress = true;\n }\n }\n\n // We disable no-unused-vars for _position. We keep position for potential reintroduction of source-map\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n emit(str: string, _position?: CssCommonPositionAST['position']) {\n return str;\n }\n\n /**\n * Increase, decrease or return current indentation.\n */\n indent(level?: number) {\n this.level = this.level || 1;\n\n if (level) {\n this.level += level;\n return '';\n }\n\n return Array(this.level).join(this.indentation);\n }\n\n visit(node: CssAllNodesAST): string {\n switch (node.type) {\n case CssTypes.stylesheet:\n return this.stylesheet(node);\n case CssTypes.rule:\n return this.rule(node);\n case CssTypes.declaration:\n return this.declaration(node);\n case CssTypes.comment:\n return this.comment(node);\n case CssTypes.charset:\n return this.charset(node);\n case CssTypes.document:\n return this.document(node);\n case CssTypes.customMedia:\n return this.customMedia(node);\n case CssTypes.fontFace:\n return this.fontFace(node);\n case CssTypes.host:\n return this.host(node);\n case CssTypes.import:\n return this.import(node);\n case CssTypes.keyframes:\n return this.keyframes(node);\n case CssTypes.keyframe:\n return this.keyframe(node);\n case CssTypes.media:\n return this.media(node);\n case CssTypes.namespace:\n return this.namespace(node);\n case CssTypes.page:\n return this.page(node);\n case CssTypes.supports:\n return this.supports(node);\n }\n }\n\n mapVisit(nodes: Array, delim?: string) {\n let buf = '';\n delim = delim || '';\n\n for (let i = 0, length = nodes.length; i < length; i++) {\n buf += this.visit(nodes[i]);\n if (delim && i < length - 1) {\n buf += this.emit(delim);\n }\n }\n\n return buf;\n }\n\n compile(node: CssStylesheetAST) {\n if (this.compress) {\n return node.stylesheet.rules.map(this.visit, this).join('');\n }\n\n return this.stylesheet(node);\n }\n\n /**\n * Visit stylesheet node.\n */\n stylesheet(node: CssStylesheetAST) {\n return this.mapVisit(node.stylesheet.rules, '\\n\\n');\n }\n\n /**\n * Visit comment node.\n */\n comment(node: CssCommentAST) {\n if (this.compress) {\n return this.emit('', node.position);\n }\n return this.emit(this.indent() + '/*' + node.comment + '*/', node.position);\n }\n\n /**\n * Visit import node.\n */\n import(node: CssImportAST) {\n return this.emit('@import ' + node.import + ';', node.position);\n }\n\n /**\n * Visit media node.\n */\n media(node: CssMediaAST) {\n if (this.compress) {\n return (\n this.emit('@media ' + node.media, node.position) +\n this.emit('{') +\n this.mapVisit(node.rules) +\n this.emit('}')\n );\n }\n return (\n this.emit('@media ' + node.media, node.position) +\n this.emit(' {\\n' + this.indent(1)) +\n this.mapVisit(node.rules, '\\n\\n') +\n this.emit(this.indent(-1) + '\\n}')\n );\n }\n\n /**\n * Visit document node.\n */\n document(node: CssDocumentAST) {\n const doc = '@' + (node.vendor || '') + 'document ' + node.document;\n if (this.compress) {\n return (\n this.emit(doc, node.position) +\n this.emit('{') +\n this.mapVisit(node.rules) +\n this.emit('}')\n );\n }\n return (\n this.emit(doc, node.position) +\n this.emit(' ' + ' {\\n' + this.indent(1)) +\n this.mapVisit(node.rules, '\\n\\n') +\n this.emit(this.indent(-1) + '\\n}')\n );\n }\n\n /**\n * Visit charset node.\n */\n charset(node: CssCharsetAST) {\n return this.emit('@charset ' + node.charset + ';', node.position);\n }\n\n /**\n * Visit namespace node.\n */\n namespace(node: CssNamespaceAST) {\n return this.emit('@namespace ' + node.namespace + ';', node.position);\n }\n\n /**\n * Visit supports node.\n */\n supports(node: CssSupportsAST) {\n if (this.compress) {\n return (\n this.emit('@supports ' + node.supports, node.position) +\n this.emit('{') +\n this.mapVisit(node.rules) +\n this.emit('}')\n );\n }\n return (\n this.emit('@supports ' + node.supports, node.position) +\n this.emit(' {\\n' + this.indent(1)) +\n this.mapVisit(node.rules, '\\n\\n') +\n this.emit(this.indent(-1) + '\\n}')\n );\n }\n\n /**\n * Visit keyframes node.\n */\n keyframes(node: CssKeyframesAST) {\n if (this.compress) {\n return (\n this.emit(\n '@' + (node.vendor || '') + 'keyframes ' + node.name,\n node.position\n ) +\n this.emit('{') +\n this.mapVisit(node.keyframes) +\n this.emit('}')\n );\n }\n return (\n this.emit(\n '@' + (node.vendor || '') + 'keyframes ' + node.name,\n node.position\n ) +\n this.emit(' {\\n' + this.indent(1)) +\n this.mapVisit(node.keyframes, '\\n') +\n this.emit(this.indent(-1) + '}')\n );\n }\n\n /**\n * Visit keyframe node.\n */\n keyframe(node: CssKeyframeAST) {\n const decls = node.declarations;\n if (this.compress) {\n return (\n this.emit(node.values.join(','), node.position) +\n this.emit('{') +\n this.mapVisit(decls) +\n this.emit('}')\n );\n }\n\n return (\n this.emit(this.indent()) +\n this.emit(node.values.join(', '), node.position) +\n this.emit(' {\\n' + this.indent(1)) +\n this.mapVisit(decls, '\\n') +\n this.emit(this.indent(-1) + '\\n' + this.indent() + '}\\n')\n );\n }\n\n /**\n * Visit page node.\n */\n page(node: CssPageAST) {\n if (this.compress) {\n const sel = node.selectors.length ? node.selectors.join(', ') : '';\n\n return (\n this.emit('@page ' + sel, node.position) +\n this.emit('{') +\n this.mapVisit(node.declarations) +\n this.emit('}')\n );\n }\n const sel = node.selectors.length ? node.selectors.join(', ') + ' ' : '';\n\n return (\n this.emit('@page ' + sel, node.position) +\n this.emit('{\\n') +\n this.emit(this.indent(1)) +\n this.mapVisit(node.declarations, '\\n') +\n this.emit(this.indent(-1)) +\n this.emit('\\n}')\n );\n }\n\n /**\n * Visit font-face node.\n */\n fontFace(node: CssFontFaceAST) {\n if (this.compress) {\n return (\n this.emit('@font-face', node.position) +\n this.emit('{') +\n this.mapVisit(node.declarations) +\n this.emit('}')\n );\n }\n return (\n this.emit('@font-face ', node.position) +\n this.emit('{\\n') +\n this.emit(this.indent(1)) +\n this.mapVisit(node.declarations, '\\n') +\n this.emit(this.indent(-1)) +\n this.emit('\\n}')\n );\n }\n\n /**\n * Visit host node.\n */\n host(node: CssHostAST) {\n if (this.compress) {\n return (\n this.emit('@host', node.position) +\n this.emit('{') +\n this.mapVisit(node.rules) +\n this.emit('}')\n );\n }\n return (\n this.emit('@host', node.position) +\n this.emit(' {\\n' + this.indent(1)) +\n this.mapVisit(node.rules, '\\n\\n') +\n this.emit(this.indent(-1) + '\\n}')\n );\n }\n\n /**\n * Visit custom-media node.\n */\n customMedia(node: CssCustomMediaAST) {\n return this.emit(\n '@custom-media ' + node.name + ' ' + node.media + ';',\n node.position\n );\n }\n\n /**\n * Visit rule node.\n */\n rule(node: CssRuleAST) {\n const decls = node.declarations;\n if (!decls.length) {\n return '';\n }\n\n if (this.compress) {\n return (\n this.emit(node.selectors.join(','), node.position) +\n this.emit('{') +\n this.mapVisit(decls) +\n this.emit('}')\n );\n }\n const indent = this.indent();\n\n return (\n this.emit(\n node.selectors\n .map(s => {\n return indent + s;\n })\n .join(',\\n'),\n node.position\n ) +\n this.emit(' {\\n') +\n this.emit(this.indent(1)) +\n this.mapVisit(decls, '\\n') +\n this.emit(this.indent(-1)) +\n this.emit('\\n' + this.indent() + '}')\n );\n }\n\n /**\n * Visit declaration node.\n */\n declaration(node: CssDeclarationAST) {\n if (this.compress) {\n return (\n this.emit(node.property + ':' + node.value, node.position) +\n this.emit(';')\n );\n }\n return (\n this.emit(this.indent()) +\n this.emit(node.property + ': ' + node.value, node.position) +\n this.emit(';')\n );\n }\n}\n\nexport default Compiler;\n","import {CssStylesheetAST} from '../type';\nimport Compiler from './compiler';\n\nexport default (\n node: CssStylesheetAST,\n options?: ConstructorParameters[0]\n) => {\n const compiler = new Compiler(options || {});\n return compiler.compile(node);\n};\n","import CssParseError from './CssParseError';\nimport Position from './CssPosition';\n\nexport enum CssTypes {\n stylesheet = 'stylesheet',\n rule = 'rule',\n declaration = 'declaration',\n comment = 'comment',\n charset = 'charset',\n document = 'document',\n customMedia = 'custom-media',\n fontFace = 'font-face',\n host = 'host',\n import = 'import',\n keyframes = 'keyframes',\n keyframe = 'keyframe',\n media = 'media',\n namespace = 'namespace',\n page = 'page',\n supports = 'supports',\n}\n\nexport type CssCommonAST = {\n type: CssTypes;\n};\n\nexport type CssCommonPositionAST = CssCommonAST & {\n position?: Position;\n parent?: unknown;\n};\n\nexport type CssStylesheetAST = CssCommonAST & {\n type: CssTypes.stylesheet;\n stylesheet: {\n source?: string;\n rules: Array;\n parsingErrors?: Array;\n };\n};\n\nexport type CssRuleAST = CssCommonPositionAST & {\n type: CssTypes.rule;\n selectors: Array;\n declarations: Array;\n};\n\nexport type CssDeclarationAST = CssCommonPositionAST & {\n type: CssTypes.declaration;\n property: string;\n value: string;\n};\n\nexport type CssCommentAST = CssCommonPositionAST & {\n type: CssTypes.comment;\n comment: string;\n};\n\nexport type CssCharsetAST = CssCommonPositionAST & {\n type: CssTypes.charset;\n charset: string;\n};\nexport type CssCustomMediaAST = CssCommonPositionAST & {\n type: CssTypes.customMedia;\n name: string;\n media: string;\n};\nexport type CssDocumentAST = CssCommonPositionAST & {\n type: CssTypes.document;\n document: string;\n vendor?: string;\n rules: Array;\n};\nexport type CssFontFaceAST = CssCommonPositionAST & {\n type: CssTypes.fontFace;\n declarations: Array;\n};\nexport type CssHostAST = CssCommonPositionAST & {\n type: CssTypes.host;\n rules: Array;\n};\nexport type CssImportAST = CssCommonPositionAST & {\n type: CssTypes.import;\n import: string;\n};\nexport type CssKeyframesAST = CssCommonPositionAST & {\n type: CssTypes.keyframes;\n name: string;\n vendor?: string;\n keyframes: Array;\n};\nexport type CssKeyframeAST = CssCommonPositionAST & {\n type: CssTypes.keyframe;\n values: Array;\n declarations: Array;\n};\nexport type CssMediaAST = CssCommonPositionAST & {\n type: CssTypes.media;\n media: string;\n rules: Array;\n};\nexport type CssNamespaceAST = CssCommonPositionAST & {\n type: CssTypes.namespace;\n namespace: string;\n};\nexport type CssPageAST = CssCommonPositionAST & {\n type: CssTypes.page;\n selectors: Array;\n declarations: Array;\n};\nexport type CssSupportsAST = CssCommonPositionAST & {\n type: CssTypes.supports;\n supports: string;\n rules: Array;\n};\n\nexport type CssAtRuleAST =\n | CssRuleAST\n | CssCommentAST\n | CssCharsetAST\n | CssCustomMediaAST\n | CssDocumentAST\n | CssFontFaceAST\n | CssHostAST\n | CssImportAST\n | CssKeyframesAST\n | CssMediaAST\n | CssNamespaceAST\n | CssPageAST\n | CssSupportsAST;\n\nexport type CssAllNodesAST =\n | CssAtRuleAST\n | CssStylesheetAST\n | CssDeclarationAST\n | CssKeyframeAST;\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(607);\n"],"names":["root","factory","exports","module","define","amd","a","i","this","CssParseError","Error","constructor","filename","msg","lineno","column","css","super","reason","line","source","start","end","default","commentre","trim","str","addParent","obj","parent","isNode","type","childParent","k","value","Array","isArray","forEach","v","Object","defineProperty","configurable","writable","enumerable","parse","options","position","node","whitespace","errorsList","error","err","silent","push","open","match","close","rules","comments","length","charAt","atrule","rule","re","m","exec","lines","lastIndexOf","updatePosition","slice","c","comment","pos","CssTypes","selector","res","replace","indexOf","split","map","s","declaration","propMatch","propValue","val","ret","property","declarations","decls","decl","keyframe","vals","values","atimport","_compileAtrule","atcharset","atnamespace","name","RegExp","m1","vendor","m2","frame","frames","concat","keyframes","atkeyframes","media","style","atmedia","customMedia","atcustommedia","supports","atsupports","doc","document","atdocument","sel","page","selectors","atpage","host","athost","fontFace","atfontface","rulesList","stylesheet","parsingErrors","level","indentation","compress","indent","emit","_position","join","visit","charset","import","namespace","mapVisit","nodes","delim","buf","compile","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","call"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/@adobe/css-tools/package.json b/node_modules/@adobe/css-tools/package.json new file mode 100644 index 0000000..ff7963b --- /dev/null +++ b/node_modules/@adobe/css-tools/package.json @@ -0,0 +1,55 @@ +{ + "name": "@adobe/css-tools", + "version": "4.0.1", + "description": "CSS parser / stringifier", + "main": "dist/umd/cssTools.js", + "module": "dist/cjs/cssTools.js", + "types": "dist/cjs/index.d.ts", + "files": [ + "dist", + "Readme.md" + ], + "devDependencies": { + "@types/benchmark": "^2.1.1", + "@types/bytes": "^3.1.1", + "@types/jest": "^28.1.1", + "@types/node": "^18.0.0", + "benchmark": "^2.1.4", + "bytes": "^3.1.0", + "gts": "^4.0.0", + "jest": "^28.1.1", + "ts-jest": "^28.0.4", + "ts-loader": "^9.3.0", + "ts-node": "^10.8.1", + "typescript": "^4.7.3", + "webpack": "^5.73.0", + "webpack-cli": "^4.9.2" + }, + "scripts": { + "benchmark": "ts-node benchmark/index.ts", + "test": "jest", + "lint": "gts lint", + "clean": "gts clean", + "build": "npm run compile", + "compile": "NODE_ENV=prod webpack --mode production", + "fix": "gts fix", + "prepare": "npm run build", + "pretest": "npm run build", + "posttest": "npm run lint" + }, + "author": "TJ Holowaychuk ", + "contributors": [ + "Jean-Philippe Zolesio " + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/adobe/css-tools.git" + }, + "keywords": [ + "css", + "parser", + "stringifier", + "stylesheet" + ] +} diff --git a/node_modules/@antfu/install-pkg/LICENSE b/node_modules/@antfu/install-pkg/LICENSE new file mode 100644 index 0000000..d47cea5 --- /dev/null +++ b/node_modules/@antfu/install-pkg/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Anthony Fu + +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/@antfu/install-pkg/README.md b/node_modules/@antfu/install-pkg/README.md new file mode 100644 index 0000000..964dc98 --- /dev/null +++ b/node_modules/@antfu/install-pkg/README.md @@ -0,0 +1,27 @@ +# install-pkg + +[![NPM version](https://img.shields.io/npm/v/@antfu/install-pkg?color=a1b858&label=)](https://www.npmjs.com/package/@antfu/install-pkg) + +Install package programmatically. Detect package managers automatically (`npm`, `yarn` and `pnpm`). + +```bash +npm i @antfu/install-pkg +``` + +```ts +import { installPackage } from '@antfu/install-pkg' + +await installPackage('vite', { silent: true }) +``` + +## Sponsors + +

+ + + +

+ +## License + +[MIT](./LICENSE) License © 2021 [Anthony Fu](https://github.com/antfu) diff --git a/node_modules/@antfu/install-pkg/dist/index.d.ts b/node_modules/@antfu/install-pkg/dist/index.d.ts new file mode 100644 index 0000000..b92eb22 --- /dev/null +++ b/node_modules/@antfu/install-pkg/dist/index.d.ts @@ -0,0 +1,19 @@ +import execa from 'execa'; + +declare type PackageManager = 'pnpm' | 'yarn' | 'npm' | 'bun'; +declare const AGENTS: readonly ["pnpm", "yarn", "npm", "pnpm@6", "yarn@berry", "bun"]; +declare type Agent = typeof AGENTS[number]; +declare function detectPackageManager(cwd?: string): Promise; + +interface InstallPackageOptions { + cwd?: string; + dev?: boolean; + silent?: boolean; + packageManager?: string; + packageManagerVersion?: string; + preferOffline?: boolean; + additionalArgs?: string[]; +} +declare function installPackage(names: string | string[], options?: InstallPackageOptions): Promise>; + +export { Agent, InstallPackageOptions, PackageManager, detectPackageManager, installPackage }; diff --git a/node_modules/@antfu/install-pkg/dist/index.js b/node_modules/@antfu/install-pkg/dist/index.js new file mode 100644 index 0000000..d828b93 --- /dev/null +++ b/node_modules/@antfu/install-pkg/dist/index.js @@ -0,0 +1,108 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + detectPackageManager: () => detectPackageManager, + installPackage: () => installPackage +}); +module.exports = __toCommonJS(src_exports); + +// src/detect.ts +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var import_find_up = __toESM(require("find-up")); +var AGENTS = ["pnpm", "yarn", "npm", "pnpm@6", "yarn@berry", "bun"]; +var LOCKS = { + "bun.lockb": "bun", + "pnpm-lock.yaml": "pnpm", + "yarn.lock": "yarn", + "package-lock.json": "npm", + "npm-shrinkwrap.json": "npm" +}; +async function detectPackageManager(cwd = process.cwd()) { + let agent = null; + const lockPath = await (0, import_find_up.default)(Object.keys(LOCKS), { cwd }); + let packageJsonPath; + if (lockPath) + packageJsonPath = import_path.default.resolve(lockPath, "../package.json"); + else + packageJsonPath = await (0, import_find_up.default)("package.json", { cwd }); + if (packageJsonPath && import_fs.default.existsSync(packageJsonPath)) { + try { + const pkg = JSON.parse(import_fs.default.readFileSync(packageJsonPath, "utf8")); + if (typeof pkg.packageManager === "string") { + const [name, version] = pkg.packageManager.split("@"); + if (name === "yarn" && parseInt(version) > 1) + agent = "yarn@berry"; + else if (name === "pnpm" && parseInt(version) < 7) + agent = "pnpm@6"; + else if (name in AGENTS) + agent = name; + else + console.warn("[ni] Unknown packageManager:", pkg.packageManager); + } + } catch { + } + } + if (!agent && lockPath) + agent = LOCKS[import_path.default.basename(lockPath)]; + return agent; +} + +// src/install.ts +var import_execa = __toESM(require("execa")); +async function installPackage(names, options = {}) { + const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm"; + const [agent] = detectedAgent.split("@"); + if (!Array.isArray(names)) + names = [names]; + const args = options.additionalArgs || []; + if (options.preferOffline) { + if (detectedAgent === "yarn@berry") + args.unshift("--cached"); + else + args.unshift("--prefer-offline"); + } + return (0, import_execa.default)( + agent, + [ + agent === "yarn" ? "add" : "install", + options.dev ? "-D" : "", + ...args, + ...names + ].filter(Boolean), + { + stdio: options.silent ? "ignore" : "inherit", + cwd: options.cwd + } + ); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + detectPackageManager, + installPackage +}); diff --git a/node_modules/@antfu/install-pkg/dist/index.mjs b/node_modules/@antfu/install-pkg/dist/index.mjs new file mode 100644 index 0000000..fe13288 --- /dev/null +++ b/node_modules/@antfu/install-pkg/dist/index.mjs @@ -0,0 +1,74 @@ +// src/detect.ts +import fs from "fs"; +import path from "path"; +import findUp from "find-up"; +var AGENTS = ["pnpm", "yarn", "npm", "pnpm@6", "yarn@berry", "bun"]; +var LOCKS = { + "bun.lockb": "bun", + "pnpm-lock.yaml": "pnpm", + "yarn.lock": "yarn", + "package-lock.json": "npm", + "npm-shrinkwrap.json": "npm" +}; +async function detectPackageManager(cwd = process.cwd()) { + let agent = null; + const lockPath = await findUp(Object.keys(LOCKS), { cwd }); + let packageJsonPath; + if (lockPath) + packageJsonPath = path.resolve(lockPath, "../package.json"); + else + packageJsonPath = await findUp("package.json", { cwd }); + if (packageJsonPath && fs.existsSync(packageJsonPath)) { + try { + const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")); + if (typeof pkg.packageManager === "string") { + const [name, version] = pkg.packageManager.split("@"); + if (name === "yarn" && parseInt(version) > 1) + agent = "yarn@berry"; + else if (name === "pnpm" && parseInt(version) < 7) + agent = "pnpm@6"; + else if (name in AGENTS) + agent = name; + else + console.warn("[ni] Unknown packageManager:", pkg.packageManager); + } + } catch { + } + } + if (!agent && lockPath) + agent = LOCKS[path.basename(lockPath)]; + return agent; +} + +// src/install.ts +import execa from "execa"; +async function installPackage(names, options = {}) { + const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm"; + const [agent] = detectedAgent.split("@"); + if (!Array.isArray(names)) + names = [names]; + const args = options.additionalArgs || []; + if (options.preferOffline) { + if (detectedAgent === "yarn@berry") + args.unshift("--cached"); + else + args.unshift("--prefer-offline"); + } + return execa( + agent, + [ + agent === "yarn" ? "add" : "install", + options.dev ? "-D" : "", + ...args, + ...names + ].filter(Boolean), + { + stdio: options.silent ? "ignore" : "inherit", + cwd: options.cwd + } + ); +} +export { + detectPackageManager, + installPackage +}; diff --git a/node_modules/@antfu/install-pkg/package.json b/node_modules/@antfu/install-pkg/package.json new file mode 100644 index 0000000..e7f570e --- /dev/null +++ b/node_modules/@antfu/install-pkg/package.json @@ -0,0 +1,53 @@ +{ + "name": "@antfu/install-pkg", + "version": "0.1.1", + "packageManager": "pnpm@7.12.0", + "description": "Install package programmatically.", + "author": "Anthony Fu ", + "license": "MIT", + "funding": "https://github.com/sponsors/antfu", + "homepage": "https://github.com/antfu/install-pkg#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/antfu/install-pkg.git" + }, + "bugs": { + "url": "https://github.com/antfu/install-pkg/issues" + }, + "keywords": [], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.js", + "import": "./dist/index.mjs" + } + }, + "main": "dist/index.js", + "module": "dist/index.mjs", + "types": "dist/index.d.ts", + "files": [ + "dist" + ], + "dependencies": { + "execa": "^5.1.1", + "find-up": "^5.0.0" + }, + "devDependencies": { + "@antfu/eslint-config": "^0.27.0", + "@antfu/ni": "^0.18.0", + "@types/node": "^16.11.59", + "bumpp": "^8.2.1", + "eslint": "^8.23.1", + "esno": "^0.16.3", + "tsup": "^6.2.3", + "typescript": "^4.8.3" + }, + "scripts": { + "dev": "nr build --watch", + "start": "esno src/index.ts", + "build": "tsup src/index.ts --format cjs,esm --dts --no-splitting", + "release": "bumpp --commit --push --tag && pnpm publish", + "lint": "eslint ." + } +} \ No newline at end of file diff --git a/node_modules/@babel/code-frame/LICENSE b/node_modules/@babel/code-frame/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/code-frame/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/code-frame/README.md b/node_modules/@babel/code-frame/README.md new file mode 100644 index 0000000..08cacb0 --- /dev/null +++ b/node_modules/@babel/code-frame/README.md @@ -0,0 +1,19 @@ +# @babel/code-frame + +> Generate errors that contain a code frame that point to source locations. + +See our website [@babel/code-frame](https://babeljs.io/docs/en/babel-code-frame) for more information. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/code-frame +``` + +or using yarn: + +```sh +yarn add @babel/code-frame --dev +``` diff --git a/node_modules/@babel/code-frame/lib/index.js b/node_modules/@babel/code-frame/lib/index.js new file mode 100644 index 0000000..cba3f83 --- /dev/null +++ b/node_modules/@babel/code-frame/lib/index.js @@ -0,0 +1,163 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.codeFrameColumns = codeFrameColumns; +exports.default = _default; + +var _highlight = require("@babel/highlight"); + +let deprecationWarningShown = false; + +function getDefs(chalk) { + return { + gutter: chalk.grey, + marker: chalk.red.bold, + message: chalk.red.bold + }; +} + +const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + +function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); + + if (startLine === -1) { + start = 0; + } + + if (endLine === -1) { + end = source.length; + } + + const lineDiff = endLine - startLine; + const markerLines = {}; + + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; + + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } + + return { + start, + end, + markerLines + }; +} + +function codeFrameColumns(rawLines, loc, opts = {}) { + const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); + const chalk = (0, _highlight.getChalk)(opts); + const defs = getDefs(chalk); + + const maybeHighlight = (chalkFn, string) => { + return highlighted ? chalkFn(string) : string; + }; + + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; + let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} |`; + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; + + if (hasMarker) { + let markerLine = ""; + + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); + + if (lastMarkerLine && opts.message) { + markerLine += " " + maybeHighlight(defs.message, opts.message); + } + } + + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); + } else { + return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`; + } + }).join("\n"); + + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } + + if (highlighted) { + return chalk.reset(frame); + } else { + return frame; + } +} + +function _default(rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); +} \ No newline at end of file diff --git a/node_modules/@babel/code-frame/package.json b/node_modules/@babel/code-frame/package.json new file mode 100644 index 0000000..18d8db1 --- /dev/null +++ b/node_modules/@babel/code-frame/package.json @@ -0,0 +1,30 @@ +{ + "name": "@babel/code-frame", + "version": "7.18.6", + "description": "Generate errors that contain a code frame that point to source locations.", + "author": "The Babel Team (https://babel.dev/team)", + "homepage": "https://babel.dev/docs/en/next/babel-code-frame", + "bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-code-frame" + }, + "main": "./lib/index.js", + "dependencies": { + "@babel/highlight": "^7.18.6" + }, + "devDependencies": { + "@types/chalk": "^2.0.0", + "chalk": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/LICENSE b/node_modules/@babel/helper-validator-identifier/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/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/helper-validator-identifier/README.md b/node_modules/@babel/helper-validator-identifier/README.md new file mode 100644 index 0000000..4f704c4 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/README.md @@ -0,0 +1,19 @@ +# @babel/helper-validator-identifier + +> Validate identifier/keywords name + +See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/en/babel-helper-validator-identifier) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-validator-identifier +``` + +or using yarn: + +```sh +yarn add @babel/helper-validator-identifier +``` diff --git a/node_modules/@babel/helper-validator-identifier/lib/identifier.js b/node_modules/@babel/helper-validator-identifier/lib/identifier.js new file mode 100644 index 0000000..3a9e335 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/identifier.js @@ -0,0 +1,86 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIdentifierChar = isIdentifierChar; +exports.isIdentifierName = isIdentifierName; +exports.isIdentifierStart = isIdentifierStart; +let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; +const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191]; +const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + +function isInAstralSet(code, set) { + let pos = 0x10000; + + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + + return false; +} + +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes); +} + +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} + +function isIdentifierName(name) { + let isFirst = true; + + for (let i = 0; i < name.length; i++) { + let cp = name.charCodeAt(i); + + if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) { + const trail = name.charCodeAt(++i); + + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + + if (isFirst) { + isFirst = false; + + if (!isIdentifierStart(cp)) { + return false; + } + } else if (!isIdentifierChar(cp)) { + return false; + } + } + + return !isFirst; +} + +//# sourceMappingURL=identifier.js.map diff --git a/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map b/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map new file mode 100644 index 0000000..45c94ff --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map @@ -0,0 +1 @@ +{"version":3,"names":["nonASCIIidentifierStartChars","nonASCIIidentifierChars","nonASCIIidentifierStart","RegExp","nonASCIIidentifier","astralIdentifierStartCodes","astralIdentifierCodes","isInAstralSet","code","set","pos","i","length","isIdentifierStart","test","String","fromCharCode","isIdentifierChar","isIdentifierName","name","isFirst","cp","charCodeAt","trail"],"sources":["../src/identifier.ts"],"sourcesContent":["import * as charCodes from \"charcodes\";\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point between 0x80 and 0xffff.\n// Generated by `scripts/generate-identifier-regex.js`.\n\n/* prettier-ignore */\nlet nonASCIIidentifierStartChars = \"\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u0870-\\u0887\\u0889-\\u088e\\u08a0-\\u08c9\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c5d\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cdd\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d04-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e86-\\u0e8a\\u0e8c-\\u0ea3\\u0ea5\\u0ea7-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u1711\\u171f-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4c\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c88\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf3\\u1cf5\\u1cf6\\u1cfa\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31bf\\u31f0-\\u31ff\\u3400-\\u4dbf\\u4e00-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7ca\\ua7d0\\ua7d1\\ua7d3\\ua7d5-\\ua7d9\\ua7f2-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab69\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\";\n/* prettier-ignore */\nlet nonASCIIidentifierChars = \"\\u200c\\u200d\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u0898-\\u089f\\u08ca-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u09fe\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0afa-\\u0aff\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b55-\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c04\\u0c3c\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0cf3\\u0d00-\\u0d03\\u0d3b\\u0d3c\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d81-\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0ebc\\u0ec8-\\u0ece\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1715\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u180f-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1abf-\\u1ace\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf4\\u1cf7-\\u1cf9\\u1dc0-\\u1dff\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua82c\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua8ff-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f\";\n\nconst nonASCIIidentifierStart = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + \"]\",\n);\nconst nonASCIIidentifier = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\",\n);\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset-encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by `scripts/generate-identifier-regex.js`.\n/* prettier-ignore */\nconst astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,68,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,4026,582,8634,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,757,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,3104,541,1507,4938,6,4191];\n/* prettier-ignore */\nconst astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,81,2,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,9,5351,0,7,14,13835,9,87,9,39,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,4706,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,983,6,110,6,6,9,4759,9,787719,239];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code: number, set: readonly number[]): boolean {\n let pos = 0x10000;\n for (let i = 0, length = set.length; i < length; i += 2) {\n pos += set[i];\n if (pos > code) return false;\n\n pos += set[i + 1];\n if (pos >= code) return true;\n }\n return false;\n}\n\n// Test whether a given character code starts an identifier.\n\nexport function isIdentifierStart(code: number): boolean {\n if (code < charCodes.uppercaseA) return code === charCodes.dollarSign;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return (\n code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))\n );\n }\n return isInAstralSet(code, astralIdentifierStartCodes);\n}\n\n// Test whether a given character is part of an identifier.\n\nexport function isIdentifierChar(code: number): boolean {\n if (code < charCodes.digit0) return code === charCodes.dollarSign;\n if (code < charCodes.colon) return true;\n if (code < charCodes.uppercaseA) return false;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));\n }\n return (\n isInAstralSet(code, astralIdentifierStartCodes) ||\n isInAstralSet(code, astralIdentifierCodes)\n );\n}\n\n// Test whether a given string is a valid identifier name\n\nexport function isIdentifierName(name: string): boolean {\n let isFirst = true;\n for (let i = 0; i < name.length; i++) {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `name` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = name.charCodeAt(i);\n if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {\n const trail = name.charCodeAt(++i);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n if (isFirst) {\n isFirst = false;\n if (!isIdentifierStart(cp)) {\n return false;\n }\n } else if (!isIdentifierChar(cp)) {\n return false;\n }\n }\n return !isFirst;\n}\n"],"mappings":";;;;;;;;AAWA,IAAIA,4BAA4B,GAAG,8qIAAnC;AAEA,IAAIC,uBAAuB,GAAG,mkFAA9B;AAEA,MAAMC,uBAAuB,GAAG,IAAIC,MAAJ,CAC9B,MAAMH,4BAAN,GAAqC,GADP,CAAhC;AAGA,MAAMI,kBAAkB,GAAG,IAAID,MAAJ,CACzB,MAAMH,4BAAN,GAAqCC,uBAArC,GAA+D,GADtC,CAA3B;AAIAD,4BAA4B,GAAGC,uBAAuB,GAAG,IAAzD;AAQA,MAAMI,0BAA0B,GAAG,CAAC,CAAD,EAAG,EAAH,EAAM,CAAN,EAAQ,EAAR,EAAW,CAAX,EAAa,EAAb,EAAgB,CAAhB,EAAkB,CAAlB,EAAoB,CAApB,EAAsB,EAAtB,EAAyB,CAAzB,EAA2B,EAA3B,EAA8B,EAA9B,EAAiC,GAAjC,EAAqC,EAArC,EAAwC,EAAxC,EAA2C,GAA3C,EAA+C,EAA/C,EAAkD,CAAlD,EAAoD,EAApD,EAAuD,EAAvD,EAA0D,EAA1D,EAA6D,EAA7D,EAAgE,EAAhE,EAAmE,CAAnE,EAAqE,EAArE,EAAwE,EAAxE,EAA2E,EAA3E,EAA8E,CAA9E,EAAgF,EAAhF,EAAmF,CAAnF,EAAqF,CAArF,EAAuF,CAAvF,EAAyF,CAAzF,EAA2F,EAA3F,EAA8F,GAA9F,EAAkG,EAAlG,EAAqG,EAArG,EAAwG,CAAxG,EAA0G,EAA1G,EAA6G,CAA7G,EAA+G,EAA/G,EAAkH,CAAlH,EAAoH,EAApH,EAAuH,EAAvH,EAA0H,EAA1H,EAA6H,CAA7H,EAA+H,EAA/H,EAAkI,CAAlI,EAAoI,CAApI,EAAsI,CAAtI,EAAwI,CAAxI,EAA0I,CAA1I,EAA4I,EAA5I,EAA+I,CAA/I,EAAiJ,EAAjJ,EAAoJ,CAApJ,EAAsJ,CAAtJ,EAAwJ,CAAxJ,EAA0J,CAA1J,EAA4J,EAA5J,EAA+J,GAA/J,EAAmK,EAAnK,EAAsK,EAAtK,EAAyK,EAAzK,EAA4K,CAA5K,EAA8K,EAA9K,EAAiL,CAAjL,EAAmL,CAAnL,EAAqL,EAArL,EAAwL,CAAxL,EAA0L,CAA1L,EAA4L,EAA5L,EAA+L,CAA/L,EAAiM,CAAjM,EAAmM,CAAnM,EAAqM,CAArM,EAAuM,EAAvM,EAA0M,CAA1M,EAA4M,CAA5M,EAA8M,CAA9M,EAAgN,CAAhN,EAAkN,CAAlN,EAAoN,EAApN,EAAuN,EAAvN,EAA0N,EAA1N,EAA6N,EAA7N,EAAgO,EAAhO,EAAmO,EAAnO,EAAsO,EAAtO,EAAyO,CAAzO,EAA2O,CAA3O,EAA6O,EAA7O,EAAgP,EAAhP,EAAmP,EAAnP,EAAsP,EAAtP,EAAyP,EAAzP,EAA4P,EAA5P,EAA+P,CAA/P,EAAiQ,CAAjQ,EAAmQ,EAAnQ,EAAsQ,CAAtQ,EAAwQ,EAAxQ,EAA2Q,CAA3Q,EAA6Q,CAA7Q,EAA+Q,CAA/Q,EAAiR,CAAjR,EAAmR,EAAnR,EAAsR,EAAtR,EAAyR,EAAzR,EAA4R,CAA5R,EAA8R,EAA9R,EAAiS,EAAjS,EAAoS,CAApS,EAAsS,CAAtS,EAAwS,EAAxS,EAA2S,EAA3S,EAA8S,EAA9S,EAAiT,EAAjT,EAAoT,EAApT,EAAuT,EAAvT,EAA0T,EAA1T,EAA6T,EAA7T,EAAgU,EAAhU,EAAmU,GAAnU,EAAuU,EAAvU,EAA0U,EAA1U,EAA6U,EAA7U,EAAgV,EAAhV,EAAmV,EAAnV,EAAsV,EAAtV,EAAyV,EAAzV,EAA4V,GAA5V,EAAgW,EAAhW,EAAmW,CAAnW,EAAqW,CAArW,EAAuW,EAAvW,EAA0W,EAA1W,EAA6W,EAA7W,EAAgX,CAAhX,EAAkX,CAAlX,EAAoX,EAApX,EAAuX,EAAvX,EAA0X,EAA1X,EAA6X,EAA7X,EAAgY,EAAhY,EAAmY,EAAnY,EAAsY,EAAtY,EAAyY,EAAzY,EAA4Y,EAA5Y,EAA+Y,EAA/Y,EAAkZ,CAAlZ,EAAoZ,CAApZ,EAAsZ,CAAtZ,EAAwZ,EAAxZ,EAA2Z,EAA3Z,EAA8Z,EAA9Z,EAAia,EAAja,EAAoa,EAApa,EAAua,EAAva,EAA0a,EAA1a,EAA6a,CAA7a,EAA+a,CAA/a,EAAib,CAAjb,EAAmb,CAAnb,EAAqb,EAArb,EAAwb,CAAxb,EAA0b,CAA1b,EAA4b,EAA5b,EAA+b,EAA/b,EAAkc,EAAlc,EAAqc,CAArc,EAAuc,EAAvc,EAA0c,CAA1c,EAA4c,CAA5c,EAA8c,CAA9c,EAAgd,EAAhd,EAAmd,EAAnd,EAAsd,CAAtd,EAAwd,EAAxd,EAA2d,EAA3d,EAA8d,CAA9d,EAAge,EAAhe,EAAme,CAAne,EAAqe,CAAre,EAAue,CAAve,EAAye,CAAze,EAA2e,CAA3e,EAA6e,CAA7e,EAA+e,EAA/e,EAAkf,CAAlf,EAAof,CAApf,EAAsf,CAAtf,EAAwf,EAAxf,EAA2f,EAA3f,EAA8f,CAA9f,EAAggB,CAAhgB,EAAkgB,CAAlgB,EAAogB,CAApgB,EAAsgB,EAAtgB,EAAygB,CAAzgB,EAA2gB,CAA3gB,EAA6gB,CAA7gB,EAA+gB,CAA/gB,EAAihB,CAAjhB,EAAmhB,CAAnhB,EAAqhB,CAArhB,EAAuhB,CAAvhB,EAAyhB,EAAzhB,EAA4hB,CAA5hB,EAA8hB,EAA9hB,EAAiiB,CAAjiB,EAAmiB,GAAniB,EAAuiB,EAAviB,EAA0iB,EAA1iB,EAA6iB,CAA7iB,EAA+iB,EAA/iB,EAAkjB,CAAljB,EAAojB,EAApjB,EAAujB,EAAvjB,EAA0jB,EAA1jB,EAA6jB,CAA7jB,EAA+jB,CAA/jB,EAAikB,CAAjkB,EAAmkB,GAAnkB,EAAukB,EAAvkB,EAA0kB,EAA1kB,EAA6kB,CAA7kB,EAA+kB,EAA/kB,EAAklB,EAAllB,EAAqlB,EAArlB,EAAwlB,CAAxlB,EAA0lB,EAA1lB,EAA6lB,EAA7lB,EAAgmB,EAAhmB,EAAmmB,CAAnmB,EAAqmB,EAArmB,EAAwmB,EAAxmB,EAA2mB,EAA3mB,EAA8mB,CAA9mB,EAAgnB,GAAhnB,EAAonB,EAApnB,EAAunB,GAAvnB,EAA2nB,EAA3nB,EAA8nB,EAA9nB,EAAioB,CAAjoB,EAAmoB,CAAnoB,EAAqoB,CAAroB,EAAuoB,CAAvoB,EAAyoB,CAAzoB,EAA2oB,CAA3oB,EAA6oB,CAA7oB,EAA+oB,CAA/oB,EAAipB,EAAjpB,EAAopB,EAAppB,EAAupB,CAAvpB,EAAypB,CAAzpB,EAA2pB,CAA3pB,EAA6pB,EAA7pB,EAAgqB,CAAhqB,EAAkqB,CAAlqB,EAAoqB,EAApqB,EAAuqB,EAAvqB,EAA0qB,CAA1qB,EAA4qB,CAA5qB,EAA8qB,CAA9qB,EAAgrB,EAAhrB,EAAmrB,CAAnrB,EAAqrB,EAArrB,EAAwrB,EAAxrB,EAA2rB,CAA3rB,EAA6rB,CAA7rB,EAA+rB,EAA/rB,EAAksB,CAAlsB,EAAosB,EAApsB,EAAusB,EAAvsB,EAA0sB,EAA1sB,EAA6sB,CAA7sB,EAA+sB,EAA/sB,EAAktB,EAAltB,EAAqtB,GAArtB,EAAytB,CAAztB,EAA2tB,CAA3tB,EAA6tB,EAA7tB,EAAguB,EAAhuB,EAAmuB,CAAnuB,EAAquB,EAAruB,EAAwuB,EAAxuB,EAA2uB,GAA3uB,EAA+uB,CAA/uB,EAAivB,CAAjvB,EAAmvB,CAAnvB,EAAqvB,CAArvB,EAAuvB,EAAvvB,EAA0vB,EAA1vB,EAA6vB,CAA7vB,EAA+vB,EAA/vB,EAAkwB,CAAlwB,EAAowB,CAApwB,EAAswB,CAAtwB,EAAwwB,CAAxwB,EAA0wB,EAA1wB,EAA6wB,EAA7wB,EAAgxB,CAAhxB,EAAkxB,GAAlxB,EAAsxB,EAAtxB,EAAyxB,EAAzxB,EAA4xB,CAA5xB,EAA8xB,CAA9xB,EAAgyB,EAAhyB,EAAmyB,CAAnyB,EAAqyB,EAAryB,EAAwyB,GAAxyB,EAA4yB,CAA5yB,EAA8yB,EAA9yB,EAAizB,GAAjzB,EAAqzB,GAArzB,EAAyzB,GAAzzB,EAA6zB,EAA7zB,EAAg0B,GAAh0B,EAAo0B,IAAp0B,EAAy0B,EAAz0B,EAA40B,EAA50B,EAA+0B,IAA/0B,EAAo1B,EAAp1B,EAAu1B,CAAv1B,EAAy1B,IAAz1B,EAA81B,GAA91B,EAAk2B,IAAl2B,EAAu2B,GAAv2B,EAA22B,CAA32B,EAA62B,EAA72B,EAAg3B,EAAh3B,EAAm3B,EAAn3B,EAAs3B,EAAt3B,EAAy3B,EAAz3B,EAA43B,EAA53B,EAA+3B,EAA/3B,EAAk4B,EAAl4B,EAAq4B,CAAr4B,EAAu4B,EAAv4B,EAA04B,EAA14B,EAA64B,CAA74B,EAA+4B,EAA/4B,EAAk5B,GAAl5B,EAAs5B,EAAt5B,EAAy5B,GAAz5B,EAA65B,EAA75B,EAAg6B,CAAh6B,EAAk6B,CAAl6B,EAAo6B,EAAp6B,EAAu6B,EAAv6B,EAA06B,EAA16B,EAA66B,CAA76B,EAA+6B,CAA/6B,EAAi7B,CAAj7B,EAAm7B,EAAn7B,EAAs7B,IAAt7B,EAA27B,CAA37B,EAA67B,IAA77B,EAAk8B,EAAl8B,EAAq8B,CAAr8B,EAAu8B,IAAv8B,EAA48B,CAA58B,EAA88B,CAA98B,EAAg9B,CAAh9B,EAAk9B,CAAl9B,EAAo9B,CAAp9B,EAAs9B,CAAt9B,EAAw9B,GAAx9B,EAA49B,EAA59B,EAA+9B,CAA/9B,EAAi+B,EAAj+B,EAAo+B,CAAp+B,EAAs+B,CAAt+B,EAAw+B,CAAx+B,EAA0+B,EAA1+B,EAA6+B,CAA7+B,EAA++B,CAA/+B,EAAi/B,GAAj/B,EAAq/B,IAAr/B,EAA0/B,GAA1/B,EAA8/B,CAA9/B,EAAggC,EAAhgC,EAAmgC,CAAngC,EAAqgC,CAArgC,EAAugC,CAAvgC,EAAygC,CAAzgC,EAA2gC,IAA3gC,EAAghC,EAAhhC,EAAmhC,CAAnhC,EAAqhC,EAArhC,EAAwhC,CAAxhC,EAA0hC,CAA1hC,EAA4hC,CAA5hC,EAA8hC,CAA9hC,EAAgiC,CAAhiC,EAAkiC,CAAliC,EAAoiC,CAApiC,EAAsiC,CAAtiC,EAAwiC,CAAxiC,EAA0iC,EAA1iC,EAA6iC,CAA7iC,EAA+iC,CAA/iC,EAAijC,CAAjjC,EAAmjC,CAAnjC,EAAqjC,CAArjC,EAAujC,EAAvjC,EAA0jC,CAA1jC,EAA4jC,CAA5jC,EAA8jC,CAA9jC,EAAgkC,CAAhkC,EAAkkC,CAAlkC,EAAokC,CAApkC,EAAskC,CAAtkC,EAAwkC,EAAxkC,EAA2kC,CAA3kC,EAA6kC,CAA7kC,EAA+kC,CAA/kC,EAAilC,CAAjlC,EAAmlC,CAAnlC,EAAqlC,CAArlC,EAAulC,CAAvlC,EAAylC,CAAzlC,EAA2lC,CAA3lC,EAA6lC,GAA7lC,EAAimC,CAAjmC,EAAmmC,EAAnmC,EAAsmC,CAAtmC,EAAwmC,EAAxmC,EAA2mC,CAA3mC,EAA6mC,EAA7mC,EAAgnC,CAAhnC,EAAknC,EAAlnC,EAAqnC,CAArnC,EAAunC,EAAvnC,EAA0nC,CAA1nC,EAA4nC,EAA5nC,EAA+nC,CAA/nC,EAAioC,EAAjoC,EAAooC,CAApoC,EAAsoC,EAAtoC,EAAyoC,CAAzoC,EAA2oC,EAA3oC,EAA8oC,CAA9oC,EAAgpC,EAAhpC,EAAmpC,CAAnpC,EAAqpC,CAArpC,EAAupC,IAAvpC,EAA4pC,EAA5pC,EAA+pC,CAA/pC,EAAiqC,CAAjqC,EAAmqC,GAAnqC,EAAuqC,EAAvqC,EAA0qC,GAA1qC,EAA8qC,EAA9qC,EAAirC,EAAjrC,EAAorC,CAAprC,EAAsrC,EAAtrC,EAAyrC,CAAzrC,EAA2rC,GAA3rC,EAA+rC,EAA/rC,EAAksC,EAAlsC,EAAqsC,EAArsC,EAAwsC,GAAxsC,EAA4sC,EAA5sC,EAA+sC,GAA/sC,EAAmtC,CAAntC,EAAqtC,CAArtC,EAAutC,CAAvtC,EAAytC,CAAztC,EAA2tC,CAA3tC,EAA6tC,CAA7tC,EAA+tC,EAA/tC,EAAkuC,CAAluC,EAAouC,GAApuC,EAAwuC,EAAxuC,EAA2uC,EAA3uC,EAA8uC,CAA9uC,EAAgvC,CAAhvC,EAAkvC,IAAlvC,EAAuvC,CAAvvC,EAAyvC,CAAzvC,EAA2vC,EAA3vC,EAA8vC,CAA9vC,EAAgwC,CAAhwC,EAAkwC,CAAlwC,EAAowC,CAApwC,EAAswC,CAAtwC,EAAwwC,CAAxwC,EAA0wC,CAA1wC,EAA4wC,CAA5wC,EAA8wC,CAA9wC,EAAgxC,CAAhxC,EAAkxC,CAAlxC,EAAoxC,CAApxC,EAAsxC,CAAtxC,EAAwxC,CAAxxC,EAA0xC,CAA1xC,EAA4xC,CAA5xC,EAA8xC,CAA9xC,EAAgyC,CAAhyC,EAAkyC,CAAlyC,EAAoyC,CAApyC,EAAsyC,CAAtyC,EAAwyC,CAAxyC,EAA0yC,CAA1yC,EAA4yC,CAA5yC,EAA8yC,CAA9yC,EAAgzC,CAAhzC,EAAkzC,CAAlzC,EAAozC,CAApzC,EAAszC,CAAtzC,EAAwzC,CAAxzC,EAA0zC,CAA1zC,EAA4zC,CAA5zC,EAA8zC,CAA9zC,EAAg0C,CAAh0C,EAAk0C,CAAl0C,EAAo0C,CAAp0C,EAAs0C,CAAt0C,EAAw0C,CAAx0C,EAA00C,CAA10C,EAA40C,CAA50C,EAA80C,CAA90C,EAAg1C,CAAh1C,EAAk1C,CAAl1C,EAAo1C,CAAp1C,EAAs1C,CAAt1C,EAAw1C,CAAx1C,EAA01C,CAA11C,EAA41C,CAA51C,EAA81C,CAA91C,EAAg2C,CAAh2C,EAAk2C,CAAl2C,EAAo2C,CAAp2C,EAAs2C,CAAt2C,EAAw2C,CAAx2C,EAA02C,CAA12C,EAA42C,EAA52C,EAA+2C,CAA/2C,EAAi3C,CAAj3C,EAAm3C,CAAn3C,EAAq3C,CAAr3C,EAAu3C,CAAv3C,EAAy3C,EAAz3C,EAA43C,IAA53C,EAAi4C,KAAj4C,EAAu4C,EAAv4C,EAA04C,IAA14C,EAA+4C,CAA/4C,EAAi5C,GAAj5C,EAAq5C,CAAr5C,EAAu5C,IAAv5C,EAA45C,EAA55C,EAA+5C,IAA/5C,EAAo6C,IAAp6C,EAAy6C,GAAz6C,EAA66C,IAA76C,EAAk7C,IAAl7C,EAAu7C,CAAv7C,EAAy7C,IAAz7C,CAAnC;AAEA,MAAMC,qBAAqB,GAAG,CAAC,GAAD,EAAK,CAAL,EAAO,GAAP,EAAW,CAAX,EAAa,GAAb,EAAiB,CAAjB,EAAmB,GAAnB,EAAuB,CAAvB,EAAyB,IAAzB,EAA8B,CAA9B,EAAgC,CAAhC,EAAkC,CAAlC,EAAoC,CAApC,EAAsC,CAAtC,EAAwC,EAAxC,EAA2C,CAA3C,EAA6C,CAA7C,EAA+C,CAA/C,EAAiD,GAAjD,EAAqD,CAArD,EAAuD,GAAvD,EAA2D,CAA3D,EAA6D,CAA7D,EAA+D,CAA/D,EAAiE,GAAjE,EAAqE,CAArE,EAAuE,EAAvE,EAA0E,CAA1E,EAA4E,EAA5E,EAA+E,EAA/E,EAAkF,EAAlF,EAAqF,CAArF,EAAuF,GAAvF,EAA2F,CAA3F,EAA6F,EAA7F,EAAgG,EAAhG,EAAmG,EAAnG,EAAsG,EAAtG,EAAyG,CAAzG,EAA2G,CAA3G,EAA6G,EAA7G,EAAgH,CAAhH,EAAkH,EAAlH,EAAqH,EAArH,EAAwH,CAAxH,EAA0H,CAA1H,EAA4H,EAA5H,EAA+H,CAA/H,EAAiI,CAAjI,EAAmI,CAAnI,EAAqI,EAArI,EAAwI,EAAxI,EAA2I,CAA3I,EAA6I,CAA7I,EAA+I,CAA/I,EAAiJ,CAAjJ,EAAmJ,EAAnJ,EAAsJ,CAAtJ,EAAwJ,EAAxJ,EAA2J,CAA3J,EAA6J,EAA7J,EAAgK,EAAhK,EAAmK,CAAnK,EAAqK,CAArK,EAAuK,CAAvK,EAAyK,EAAzK,EAA4K,EAA5K,EAA+K,EAA/K,EAAkL,CAAlL,EAAoL,CAApL,EAAsL,CAAtL,EAAwL,CAAxL,EAA0L,GAA1L,EAA8L,EAA9L,EAAiM,CAAjM,EAAmM,CAAnM,EAAqM,CAArM,EAAuM,CAAvM,EAAyM,EAAzM,EAA4M,CAA5M,EAA8M,CAA9M,EAAgN,CAAhN,EAAkN,CAAlN,EAAoN,CAApN,EAAsN,CAAtN,EAAwN,CAAxN,EAA0N,EAA1N,EAA6N,CAA7N,EAA+N,EAA/N,EAAkO,CAAlO,EAAoO,CAApO,EAAsO,CAAtO,EAAwO,CAAxO,EAA0O,CAA1O,EAA4O,GAA5O,EAAgP,EAAhP,EAAmP,EAAnP,EAAsP,CAAtP,EAAwP,CAAxP,EAA0P,CAA1P,EAA4P,EAA5P,EAA+P,EAA/P,EAAkQ,EAAlQ,EAAqQ,CAArQ,EAAuQ,GAAvQ,EAA2Q,CAA3Q,EAA6Q,CAA7Q,EAA+Q,CAA/Q,EAAiR,EAAjR,EAAoR,CAApR,EAAsR,EAAtR,EAAyR,EAAzR,EAA4R,EAA5R,EAA+R,CAA/R,EAAiS,EAAjS,EAAoS,EAApS,EAAuS,CAAvS,EAAyS,CAAzS,EAA2S,EAA3S,EAA8S,EAA9S,EAAiT,CAAjT,EAAmT,CAAnT,EAAqT,GAArT,EAAyT,EAAzT,EAA4T,GAA5T,EAAgU,CAAhU,EAAkU,EAAlU,EAAqU,CAArU,EAAuU,CAAvU,EAAyU,CAAzU,EAA2U,CAA3U,EAA6U,CAA7U,EAA+U,CAA/U,EAAiV,CAAjV,EAAmV,CAAnV,EAAqV,CAArV,EAAuV,EAAvV,EAA0V,CAA1V,EAA4V,GAA5V,EAAgW,CAAhW,EAAkW,CAAlW,EAAoW,CAApW,EAAsW,CAAtW,EAAwW,CAAxW,EAA0W,EAA1W,EAA6W,CAA7W,EAA+W,EAA/W,EAAkX,CAAlX,EAAoX,CAApX,EAAsX,CAAtX,EAAwX,CAAxX,EAA0X,CAA1X,EAA4X,EAA5X,EAA+X,EAA/X,EAAkY,EAAlY,EAAqY,EAArY,EAAwY,GAAxY,EAA4Y,CAA5Y,EAA8Y,CAA9Y,EAAgZ,CAAhZ,EAAkZ,EAAlZ,EAAqZ,CAArZ,EAAuZ,EAAvZ,EAA0Z,EAA1Z,EAA6Z,CAA7Z,EAA+Z,EAA/Z,EAAka,GAAla,EAAsa,CAAta,EAAwa,CAAxa,EAA0a,CAA1a,EAA4a,CAA5a,EAA8a,CAA9a,EAAgb,CAAhb,EAAkb,CAAlb,EAAob,CAApb,EAAsb,CAAtb,EAAwb,CAAxb,EAA0b,CAA1b,EAA4b,EAA5b,EAA+b,CAA/b,EAAic,CAAjc,EAAmc,CAAnc,EAAqc,CAArc,EAAuc,CAAvc,EAAyc,CAAzc,EAA2c,CAA3c,EAA6c,GAA7c,EAAid,CAAjd,EAAmd,EAAnd,EAAsd,CAAtd,EAAwd,CAAxd,EAA0d,CAA1d,EAA4d,EAA5d,EAA+d,CAA/d,EAAie,CAAje,EAAme,CAAne,EAAqe,EAAre,EAAwe,CAAxe,EAA0e,IAA1e,EAA+e,CAA/e,EAAif,CAAjf,EAAmf,EAAnf,EAAsf,KAAtf,EAA4f,CAA5f,EAA8f,EAA9f,EAAigB,CAAjgB,EAAmgB,EAAngB,EAAsgB,CAAtgB,EAAwgB,EAAxgB,EAA2gB,CAA3gB,EAA6gB,EAA7gB,EAAghB,CAAhhB,EAAkhB,IAAlhB,EAAuhB,CAAvhB,EAAyhB,CAAzhB,EAA2hB,EAA3hB,EAA8hB,CAA9hB,EAAgiB,CAAhiB,EAAkiB,EAAliB,EAAqiB,CAAriB,EAAuiB,EAAviB,EAA0iB,CAA1iB,EAA4iB,KAA5iB,EAAkjB,CAAljB,EAAojB,IAApjB,EAAyjB,EAAzjB,EAA4jB,CAA5jB,EAA8jB,EAA9jB,EAAikB,GAAjkB,EAAqkB,CAArkB,EAAukB,CAAvkB,EAAykB,CAAzkB,EAA2kB,CAA3kB,EAA6kB,CAA7kB,EAA+kB,CAA/kB,EAAilB,CAAjlB,EAAmlB,EAAnlB,EAAslB,CAAtlB,EAAwlB,GAAxlB,EAA4lB,CAA5lB,EAA8lB,IAA9lB,EAAmmB,EAAnmB,EAAsmB,GAAtmB,EAA0mB,EAA1mB,EAA6mB,CAA7mB,EAA+mB,EAA/mB,EAAknB,CAAlnB,EAAonB,CAApnB,EAAsnB,EAAtnB,EAAynB,CAAznB,EAA2nB,EAA3nB,EAA8nB,CAA9nB,EAAgoB,CAAhoB,EAAkoB,EAAloB,EAAqoB,IAAroB,EAA0oB,CAA1oB,EAA4oB,CAA5oB,EAA8oB,EAA9oB,EAAipB,CAAjpB,EAAmpB,CAAnpB,EAAqpB,CAArpB,EAAupB,CAAvpB,EAAypB,CAAzpB,EAA2pB,CAA3pB,EAA6pB,GAA7pB,EAAiqB,CAAjqB,EAAmqB,GAAnqB,EAAuqB,CAAvqB,EAAyqB,EAAzqB,EAA4qB,CAA5qB,EAA8qB,GAA9qB,EAAkrB,CAAlrB,EAAorB,EAAprB,EAAurB,EAAvrB,EAA0rB,GAA1rB,EAA8rB,EAA9rB,EAAisB,GAAjsB,EAAqsB,CAArsB,EAAusB,GAAvsB,EAA2sB,CAA3sB,EAA6sB,CAA7sB,EAA+sB,CAA/sB,EAAitB,IAAjtB,EAAstB,CAAttB,EAAwtB,MAAxtB,EAA+tB,GAA/tB,CAA9B;;AAKA,SAASC,aAAT,CAAuBC,IAAvB,EAAqCC,GAArC,EAAsE;EACpE,IAAIC,GAAG,GAAG,OAAV;;EACA,KAAK,IAAIC,CAAC,GAAG,CAAR,EAAWC,MAAM,GAAGH,GAAG,CAACG,MAA7B,EAAqCD,CAAC,GAAGC,MAAzC,EAAiDD,CAAC,IAAI,CAAtD,EAAyD;IACvDD,GAAG,IAAID,GAAG,CAACE,CAAD,CAAV;IACA,IAAID,GAAG,GAAGF,IAAV,EAAgB,OAAO,KAAP;IAEhBE,GAAG,IAAID,GAAG,CAACE,CAAC,GAAG,CAAL,CAAV;IACA,IAAID,GAAG,IAAIF,IAAX,EAAiB,OAAO,IAAP;EAClB;;EACD,OAAO,KAAP;AACD;;AAIM,SAASK,iBAAT,CAA2BL,IAA3B,EAAkD;EACvD,IAAIA,IAAI,KAAR,EAAiC,OAAOA,IAAI,OAAX;EACjC,IAAIA,IAAI,MAAR,EAAkC,OAAO,IAAP;EAClC,IAAIA,IAAI,KAAR,EAAiC,OAAOA,IAAI,OAAX;EACjC,IAAIA,IAAI,OAAR,EAAkC,OAAO,IAAP;;EAClC,IAAIA,IAAI,IAAI,MAAZ,EAAoB;IAClB,OACEA,IAAI,IAAI,IAAR,IAAgBN,uBAAuB,CAACY,IAAxB,CAA6BC,MAAM,CAACC,YAAP,CAAoBR,IAApB,CAA7B,CADlB;EAGD;;EACD,OAAOD,aAAa,CAACC,IAAD,EAAOH,0BAAP,CAApB;AACD;;AAIM,SAASY,gBAAT,CAA0BT,IAA1B,EAAiD;EACtD,IAAIA,IAAI,KAAR,EAA6B,OAAOA,IAAI,OAAX;EAC7B,IAAIA,IAAI,KAAR,EAA4B,OAAO,IAAP;EAC5B,IAAIA,IAAI,KAAR,EAAiC,OAAO,KAAP;EACjC,IAAIA,IAAI,MAAR,EAAkC,OAAO,IAAP;EAClC,IAAIA,IAAI,KAAR,EAAiC,OAAOA,IAAI,OAAX;EACjC,IAAIA,IAAI,OAAR,EAAkC,OAAO,IAAP;;EAClC,IAAIA,IAAI,IAAI,MAAZ,EAAoB;IAClB,OAAOA,IAAI,IAAI,IAAR,IAAgBJ,kBAAkB,CAACU,IAAnB,CAAwBC,MAAM,CAACC,YAAP,CAAoBR,IAApB,CAAxB,CAAvB;EACD;;EACD,OACED,aAAa,CAACC,IAAD,EAAOH,0BAAP,CAAb,IACAE,aAAa,CAACC,IAAD,EAAOF,qBAAP,CAFf;AAID;;AAIM,SAASY,gBAAT,CAA0BC,IAA1B,EAAiD;EACtD,IAAIC,OAAO,GAAG,IAAd;;EACA,KAAK,IAAIT,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGQ,IAAI,CAACP,MAAzB,EAAiCD,CAAC,EAAlC,EAAsC;IAKpC,IAAIU,EAAE,GAAGF,IAAI,CAACG,UAAL,CAAgBX,CAAhB,CAAT;;IACA,IAAI,CAACU,EAAE,GAAG,MAAN,MAAkB,MAAlB,IAA4BV,CAAC,GAAG,CAAJ,GAAQQ,IAAI,CAACP,MAA7C,EAAqD;MACnD,MAAMW,KAAK,GAAGJ,IAAI,CAACG,UAAL,CAAgB,EAAEX,CAAlB,CAAd;;MACA,IAAI,CAACY,KAAK,GAAG,MAAT,MAAqB,MAAzB,EAAiC;QAC/BF,EAAE,GAAG,WAAW,CAACA,EAAE,GAAG,KAAN,KAAgB,EAA3B,KAAkCE,KAAK,GAAG,KAA1C,CAAL;MACD;IACF;;IACD,IAAIH,OAAJ,EAAa;MACXA,OAAO,GAAG,KAAV;;MACA,IAAI,CAACP,iBAAiB,CAACQ,EAAD,CAAtB,EAA4B;QAC1B,OAAO,KAAP;MACD;IACF,CALD,MAKO,IAAI,CAACJ,gBAAgB,CAACI,EAAD,CAArB,EAA2B;MAChC,OAAO,KAAP;IACD;EACF;;EACD,OAAO,CAACD,OAAR;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/lib/index.js b/node_modules/@babel/helper-validator-identifier/lib/index.js new file mode 100644 index 0000000..076eafd --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/index.js @@ -0,0 +1,59 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return _identifier.isIdentifierChar; + } +}); +Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return _identifier.isIdentifierName; + } +}); +Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return _identifier.isIdentifierStart; + } +}); +Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return _keyword.isKeyword; + } +}); +Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return _keyword.isReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindOnlyReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindReservedWord; + } +}); +Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictReservedWord; + } +}); + +var _identifier = require("./identifier"); + +var _keyword = require("./keyword"); + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/helper-validator-identifier/lib/index.js.map b/node_modules/@babel/helper-validator-identifier/lib/index.js.map new file mode 100644 index 0000000..13266b9 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":[],"sources":["../src/index.ts"],"sourcesContent":["export {\n isIdentifierName,\n isIdentifierChar,\n isIdentifierStart,\n} from \"./identifier\";\nexport {\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"./keyword\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;AAKA"} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/lib/keyword.js b/node_modules/@babel/helper-validator-identifier/lib/keyword.js new file mode 100644 index 0000000..ff6277b --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/keyword.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isKeyword = isKeyword; +exports.isReservedWord = isReservedWord; +exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; +exports.isStrictBindReservedWord = isStrictBindReservedWord; +exports.isStrictReservedWord = isStrictReservedWord; +const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +const keywords = new Set(reservedWords.keyword); +const reservedWordsStrictSet = new Set(reservedWords.strict); +const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); + +function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; +} + +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} + +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} + +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); +} + +function isKeyword(word) { + return keywords.has(word); +} + +//# sourceMappingURL=keyword.js.map diff --git a/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map b/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map new file mode 100644 index 0000000..2de8c3e --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map @@ -0,0 +1 @@ +{"version":3,"names":["reservedWords","keyword","strict","strictBind","keywords","Set","reservedWordsStrictSet","reservedWordsStrictBindSet","isReservedWord","word","inModule","isStrictReservedWord","has","isStrictBindOnlyReservedWord","isStrictBindReservedWord","isKeyword"],"sources":["../src/keyword.ts"],"sourcesContent":["const reservedWords = {\n keyword: [\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n ],\n strict: [\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n ],\n strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n word: string,\n inModule: boolean,\n): boolean {\n return (\n isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n );\n}\n\nexport function isKeyword(word: string): boolean {\n return keywords.has(word);\n}\n"],"mappings":";;;;;;;;;;AAAA,MAAMA,aAAa,GAAG;EACpBC,OAAO,EAAE,CACP,OADO,EAEP,MAFO,EAGP,OAHO,EAIP,UAJO,EAKP,UALO,EAMP,SANO,EAOP,IAPO,EAQP,MARO,EASP,SATO,EAUP,KAVO,EAWP,UAXO,EAYP,IAZO,EAaP,QAbO,EAcP,QAdO,EAeP,OAfO,EAgBP,KAhBO,EAiBP,KAjBO,EAkBP,OAlBO,EAmBP,OAnBO,EAoBP,MApBO,EAqBP,KArBO,EAsBP,MAtBO,EAuBP,OAvBO,EAwBP,OAxBO,EAyBP,SAzBO,EA0BP,QA1BO,EA2BP,QA3BO,EA4BP,MA5BO,EA6BP,MA7BO,EA8BP,OA9BO,EA+BP,IA/BO,EAgCP,YAhCO,EAiCP,QAjCO,EAkCP,MAlCO,EAmCP,QAnCO,CADW;EAsCpBC,MAAM,EAAE,CACN,YADM,EAEN,WAFM,EAGN,KAHM,EAIN,SAJM,EAKN,SALM,EAMN,WANM,EAON,QAPM,EAQN,QARM,EASN,OATM,CAtCY;EAiDpBC,UAAU,EAAE,CAAC,MAAD,EAAS,WAAT;AAjDQ,CAAtB;AAmDA,MAAMC,QAAQ,GAAG,IAAIC,GAAJ,CAAQL,aAAa,CAACC,OAAtB,CAAjB;AACA,MAAMK,sBAAsB,GAAG,IAAID,GAAJ,CAAQL,aAAa,CAACE,MAAtB,CAA/B;AACA,MAAMK,0BAA0B,GAAG,IAAIF,GAAJ,CAAQL,aAAa,CAACG,UAAtB,CAAnC;;AAKO,SAASK,cAAT,CAAwBC,IAAxB,EAAsCC,QAAtC,EAAkE;EACvE,OAAQA,QAAQ,IAAID,IAAI,KAAK,OAAtB,IAAkCA,IAAI,KAAK,MAAlD;AACD;;AAOM,SAASE,oBAAT,CAA8BF,IAA9B,EAA4CC,QAA5C,EAAwE;EAC7E,OAAOF,cAAc,CAACC,IAAD,EAAOC,QAAP,CAAd,IAAkCJ,sBAAsB,CAACM,GAAvB,CAA2BH,IAA3B,CAAzC;AACD;;AAMM,SAASI,4BAAT,CAAsCJ,IAAtC,EAA6D;EAClE,OAAOF,0BAA0B,CAACK,GAA3B,CAA+BH,IAA/B,CAAP;AACD;;AAOM,SAASK,wBAAT,CACLL,IADK,EAELC,QAFK,EAGI;EACT,OACEC,oBAAoB,CAACF,IAAD,EAAOC,QAAP,CAApB,IAAwCG,4BAA4B,CAACJ,IAAD,CADtE;AAGD;;AAEM,SAASM,SAAT,CAAmBN,IAAnB,EAA0C;EAC/C,OAAOL,QAAQ,CAACQ,GAAT,CAAaH,IAAb,CAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/package.json b/node_modules/@babel/helper-validator-identifier/package.json new file mode 100644 index 0000000..6e7de1e --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/package.json @@ -0,0 +1,28 @@ +{ + "name": "@babel/helper-validator-identifier", + "version": "7.19.1", + "description": "Validate identifier/keywords name", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-helper-validator-identifier" + }, + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "main": "./lib/index.js", + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "devDependencies": { + "@unicode/unicode-15.0.0": "^1.3.1", + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "author": "The Babel Team (https://babel.dev/team)", + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js b/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js new file mode 100644 index 0000000..aca8710 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js @@ -0,0 +1,75 @@ +"use strict"; + +// Always use the latest available version of Unicode! +// https://tc39.github.io/ecma262/#sec-conformance +const version = "15.0.0"; + +const start = require("@unicode/unicode-" + + version + + "/Binary_Property/ID_Start/code-points.js").filter(function (ch) { + return ch > 0x7f; +}); +let last = -1; +const cont = [0x200c, 0x200d].concat( + require("@unicode/unicode-" + + version + + "/Binary_Property/ID_Continue/code-points.js").filter(function (ch) { + return ch > 0x7f && search(start, ch, last + 1) == -1; + }) +); + +function search(arr, ch, starting) { + for (let i = starting; arr[i] <= ch && i < arr.length; last = i++) { + if (arr[i] === ch) return i; + } + return -1; +} + +function pad(str, width) { + while (str.length < width) str = "0" + str; + return str; +} + +function esc(code) { + const hex = code.toString(16); + if (hex.length <= 2) return "\\x" + pad(hex, 2); + else return "\\u" + pad(hex, 4); +} + +function generate(chars) { + const astral = []; + let re = ""; + for (let i = 0, at = 0x10000; i < chars.length; i++) { + const from = chars[i]; + let to = from; + while (i < chars.length - 1 && chars[i + 1] == to + 1) { + i++; + to++; + } + if (to <= 0xffff) { + if (from == to) re += esc(from); + else if (from + 1 == to) re += esc(from) + esc(to); + else re += esc(from) + "-" + esc(to); + } else { + astral.push(from - at, to - from); + at = to; + } + } + return { nonASCII: re, astral: astral }; +} + +const startData = generate(start); +const contData = generate(cont); + +console.log("/* prettier-ignore */"); +console.log('let nonASCIIidentifierStartChars = "' + startData.nonASCII + '";'); +console.log("/* prettier-ignore */"); +console.log('let nonASCIIidentifierChars = "' + contData.nonASCII + '";'); +console.log("/* prettier-ignore */"); +console.log( + "const astralIdentifierStartCodes = " + JSON.stringify(startData.astral) + ";" +); +console.log("/* prettier-ignore */"); +console.log( + "const astralIdentifierCodes = " + JSON.stringify(contData.astral) + ";" +); diff --git a/node_modules/@babel/highlight/LICENSE b/node_modules/@babel/highlight/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/highlight/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/highlight/README.md b/node_modules/@babel/highlight/README.md new file mode 100644 index 0000000..f8887ad --- /dev/null +++ b/node_modules/@babel/highlight/README.md @@ -0,0 +1,19 @@ +# @babel/highlight + +> Syntax highlight JavaScript strings for output in terminals. + +See our website [@babel/highlight](https://babeljs.io/docs/en/babel-highlight) for more information. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/highlight +``` + +or using yarn: + +```sh +yarn add @babel/highlight --dev +``` diff --git a/node_modules/@babel/highlight/lib/index.js b/node_modules/@babel/highlight/lib/index.js new file mode 100644 index 0000000..856dfd9 --- /dev/null +++ b/node_modules/@babel/highlight/lib/index.js @@ -0,0 +1,116 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = highlight; +exports.getChalk = getChalk; +exports.shouldHighlight = shouldHighlight; + +var _jsTokens = require("js-tokens"); + +var _helperValidatorIdentifier = require("@babel/helper-validator-identifier"); + +var _chalk = require("chalk"); + +const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]); + +function getDefs(chalk) { + return { + keyword: chalk.cyan, + capitalized: chalk.yellow, + jsxIdentifier: chalk.yellow, + punctuator: chalk.yellow, + number: chalk.magenta, + string: chalk.green, + regex: chalk.magenta, + comment: chalk.grey, + invalid: chalk.white.bgRed.bold + }; +} + +const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; +const BRACKET = /^[()[\]{}]$/; +let tokenize; +{ + const JSX_TAG = /^[a-z][\w-]*$/i; + + const getTokenType = function (token, offset, text) { + if (token.type === "name") { + if ((0, _helperValidatorIdentifier.isKeyword)(token.value) || (0, _helperValidatorIdentifier.isStrictReservedWord)(token.value, true) || sometimesKeywords.has(token.value)) { + return "keyword"; + } + + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) == " colorize(str)).join("\n"); + } else { + highlighted += value; + } + } + + return highlighted; +} + +function shouldHighlight(options) { + return !!_chalk.supportsColor || options.forceColor; +} + +function getChalk(options) { + return options.forceColor ? new _chalk.constructor({ + enabled: true, + level: 1 + }) : _chalk; +} + +function highlight(code, options = {}) { + if (code !== "" && shouldHighlight(options)) { + const chalk = getChalk(options); + const defs = getDefs(chalk); + return highlightTokens(defs, code); + } else { + return code; + } +} \ No newline at end of file diff --git a/node_modules/@babel/highlight/node_modules/ansi-styles/index.js b/node_modules/@babel/highlight/node_modules/ansi-styles/index.js new file mode 100644 index 0000000..90a871c --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/ansi-styles/index.js @@ -0,0 +1,165 @@ +'use strict'; +const colorConvert = require('color-convert'); + +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); diff --git a/node_modules/@babel/highlight/node_modules/ansi-styles/license b/node_modules/@babel/highlight/node_modules/ansi-styles/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/ansi-styles/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/highlight/node_modules/ansi-styles/package.json b/node_modules/@babel/highlight/node_modules/ansi-styles/package.json new file mode 100644 index 0000000..65edb48 --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/ansi-styles/package.json @@ -0,0 +1,56 @@ +{ + "name": "ansi-styles", + "version": "3.2.1", + "description": "ANSI escape codes for styling strings in the terminal", + "license": "MIT", + "repository": "chalk/ansi-styles", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava", + "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" + }, + "files": [ + "index.js" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "color-convert": "^1.9.0" + }, + "devDependencies": { + "ava": "*", + "babel-polyfill": "^6.23.0", + "svg-term-cli": "^2.1.1", + "xo": "*" + }, + "ava": { + "require": "babel-polyfill" + } +} diff --git a/node_modules/@babel/highlight/node_modules/ansi-styles/readme.md b/node_modules/@babel/highlight/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000..3158e2d --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/ansi-styles/readme.md @@ -0,0 +1,147 @@ +# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) + +> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. + + + + +## Install + +``` +$ npm install ansi-styles +``` + + +## Usage + +```js +const style = require('ansi-styles'); + +console.log(`${style.green.open}Hello world!${style.green.close}`); + + +// Color conversion between 16/256/truecolor +// NOTE: If conversion goes to 16 colors or 256 colors, the original color +// may be degraded to fit that color palette. This means terminals +// that do not support 16 million colors will best-match the +// original color. +console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); +console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); +console.log(style.color.ansi16m.hex('#ABCDEF') + 'Hello world!' + style.color.close); +``` + +## API + +Each style has an `open` and `close` property. + + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(Not widely supported)* +- `underline` +- `inverse` +- `hidden` +- `strikethrough` *(Not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `gray` ("bright black") +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` +- `bgRedBright` +- `bgGreenBright` +- `bgYellowBright` +- `bgBlueBright` +- `bgMagentaBright` +- `bgCyanBright` +- `bgWhiteBright` + + +## Advanced usage + +By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `style.modifier` +- `style.color` +- `style.bgColor` + +###### Example + +```js +console.log(style.color.green.open); +``` + +Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. + +###### Example + +```js +console.log(style.codes.get(36)); +//=> 39 +``` + + +## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) + +`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. + +To use these, call the associated conversion function with the intended output, for example: + +```js +style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code +style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code + +style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code +style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code + +style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code +style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code +``` + + +## Related + +- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +## License + +MIT diff --git a/node_modules/@babel/highlight/node_modules/chalk/index.js b/node_modules/@babel/highlight/node_modules/chalk/index.js new file mode 100644 index 0000000..1cc5fa8 --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/chalk/index.js @@ -0,0 +1,228 @@ +'use strict'; +const escapeStringRegexp = require('escape-string-regexp'); +const ansiStyles = require('ansi-styles'); +const stdoutColor = require('supports-color').stdout; + +const template = require('./templates.js'); + +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); + +const styles = Object.create(null); + +function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} + +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); +} + +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} + +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} + +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; + +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, styles); + +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} + +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + + return str; +} + +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return template(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript diff --git a/node_modules/@babel/highlight/node_modules/chalk/index.js.flow b/node_modules/@babel/highlight/node_modules/chalk/index.js.flow new file mode 100644 index 0000000..622caaa --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/chalk/index.js.flow @@ -0,0 +1,93 @@ +// @flow strict + +type TemplateStringsArray = $ReadOnlyArray; + +export type Level = $Values<{ + None: 0, + Basic: 1, + Ansi256: 2, + TrueColor: 3 +}>; + +export type ChalkOptions = {| + enabled?: boolean, + level?: Level +|}; + +export type ColorSupport = {| + level: Level, + hasBasic: boolean, + has256: boolean, + has16m: boolean +|}; + +export interface Chalk { + (...text: string[]): string, + (text: TemplateStringsArray, ...placeholders: string[]): string, + constructor(options?: ChalkOptions): Chalk, + enabled: boolean, + level: Level, + rgb(r: number, g: number, b: number): Chalk, + hsl(h: number, s: number, l: number): Chalk, + hsv(h: number, s: number, v: number): Chalk, + hwb(h: number, w: number, b: number): Chalk, + bgHex(color: string): Chalk, + bgKeyword(color: string): Chalk, + bgRgb(r: number, g: number, b: number): Chalk, + bgHsl(h: number, s: number, l: number): Chalk, + bgHsv(h: number, s: number, v: number): Chalk, + bgHwb(h: number, w: number, b: number): Chalk, + hex(color: string): Chalk, + keyword(color: string): Chalk, + + +reset: Chalk, + +bold: Chalk, + +dim: Chalk, + +italic: Chalk, + +underline: Chalk, + +inverse: Chalk, + +hidden: Chalk, + +strikethrough: Chalk, + + +visible: Chalk, + + +black: Chalk, + +red: Chalk, + +green: Chalk, + +yellow: Chalk, + +blue: Chalk, + +magenta: Chalk, + +cyan: Chalk, + +white: Chalk, + +gray: Chalk, + +grey: Chalk, + +blackBright: Chalk, + +redBright: Chalk, + +greenBright: Chalk, + +yellowBright: Chalk, + +blueBright: Chalk, + +magentaBright: Chalk, + +cyanBright: Chalk, + +whiteBright: Chalk, + + +bgBlack: Chalk, + +bgRed: Chalk, + +bgGreen: Chalk, + +bgYellow: Chalk, + +bgBlue: Chalk, + +bgMagenta: Chalk, + +bgCyan: Chalk, + +bgWhite: Chalk, + +bgBlackBright: Chalk, + +bgRedBright: Chalk, + +bgGreenBright: Chalk, + +bgYellowBright: Chalk, + +bgBlueBright: Chalk, + +bgMagentaBright: Chalk, + +bgCyanBright: Chalk, + +bgWhiteBrigh: Chalk, + + supportsColor: ColorSupport +}; + +declare module.exports: Chalk; diff --git a/node_modules/@babel/highlight/node_modules/chalk/license b/node_modules/@babel/highlight/node_modules/chalk/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/chalk/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/highlight/node_modules/chalk/package.json b/node_modules/@babel/highlight/node_modules/chalk/package.json new file mode 100644 index 0000000..bc32468 --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/chalk/package.json @@ -0,0 +1,71 @@ +{ + "name": "chalk", + "version": "2.4.2", + "description": "Terminal string styling done right", + "license": "MIT", + "repository": "chalk/chalk", + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && tsc --project types && flow --max-warnings=0 && nyc ava", + "bench": "matcha benchmark.js", + "coveralls": "nyc report --reporter=text-lcov | coveralls" + }, + "files": [ + "index.js", + "templates.js", + "types/index.d.ts", + "index.js.flow" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "str", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "devDependencies": { + "ava": "*", + "coveralls": "^3.0.0", + "execa": "^0.9.0", + "flow-bin": "^0.68.0", + "import-fresh": "^2.0.0", + "matcha": "^0.7.0", + "nyc": "^11.0.2", + "resolve-from": "^4.0.0", + "typescript": "^2.5.3", + "xo": "*" + }, + "types": "types/index.d.ts", + "xo": { + "envs": [ + "node", + "mocha" + ], + "ignores": [ + "test/_flow.js" + ] + } +} diff --git a/node_modules/@babel/highlight/node_modules/chalk/readme.md b/node_modules/@babel/highlight/node_modules/chalk/readme.md new file mode 100644 index 0000000..d298e2c --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/chalk/readme.md @@ -0,0 +1,314 @@ +

+
+
+ Chalk +
+
+
+

+ +> Terminal string styling done right + +[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) [![Mentioned in Awesome Node.js](https://awesome.re/mentioned-badge.svg)](https://github.com/sindresorhus/awesome-nodejs) + +### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0) + + + + +## Highlights + +- Expressive API +- Highly performant +- Ability to nest styles +- [256/Truecolor color support](#256-and-truecolor-color-support) +- Auto-detects color support +- Doesn't extend `String.prototype` +- Clean and focused +- Actively maintained +- [Used by ~23,000 packages](https://www.npmjs.com/browse/depended/chalk) as of December 31, 2017 + + +## Install + +```console +$ npm install chalk +``` + + + + + + +## Usage + +```js +const chalk = require('chalk'); + +console.log(chalk.blue('Hello world!')); +``` + +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. + +```js +const chalk = require('chalk'); +const log = console.log; + +// Combine styled and normal strings +log(chalk.blue('Hello') + ' World' + chalk.red('!')); + +// Compose multiple styles using the chainable API +log(chalk.blue.bgRed.bold('Hello world!')); + +// Pass in multiple arguments +log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); + +// Nest styles +log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); + +// Nest styles of the same type even (color, underline, background) +log(chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +)); + +// ES2015 template literal +log(` +CPU: ${chalk.red('90%')} +RAM: ${chalk.green('40%')} +DISK: ${chalk.yellow('70%')} +`); + +// ES2015 tagged template literal +log(chalk` +CPU: {red ${cpu.totalPercent}%} +RAM: {green ${ram.used / ram.total * 100}%} +DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} +`); + +// Use RGB colors in terminal emulators that support it. +log(chalk.keyword('orange')('Yay for orange colored text!')); +log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); +log(chalk.hex('#DEADED').bold('Bold gray!')); +``` + +Easily define your own themes: + +```js +const chalk = require('chalk'); + +const error = chalk.bold.red; +const warning = chalk.keyword('orange'); + +console.log(error('Error!')); +console.log(warning('Warning!')); +``` + +Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): + +```js +const name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> 'Hello Sindre' +``` + + +## API + +### chalk.` + + + + + \ No newline at end of file diff --git a/node_modules/imba/src/templates/serve-html.imba b/node_modules/imba/src/templates/serve-html.imba new file mode 100644 index 0000000..dce1313 --- /dev/null +++ b/node_modules/imba/src/templates/serve-html.imba @@ -0,0 +1,14 @@ +import http from 'http' +import index from '__ENTRYPOINT__' +import {serve} from 'imba/src/imba/serve.imba' + +const server = http.createServer do(req,res) + let body = index.body + # potentially inject hmr script + if global.IMBA_HMR_PATH and body.indexOf('__hmr__.js') == -1 + body = "" + body + res.writeHead(200,{'Content-Type': 'text/html'}) + res.end body + + +serve( server.listen(Number(process.env.PORT || 3000)) ) \ No newline at end of file diff --git a/node_modules/imba/src/templates/serve-http.imba b/node_modules/imba/src/templates/serve-http.imba new file mode 100644 index 0000000..e2cc69e --- /dev/null +++ b/node_modules/imba/src/templates/serve-http.imba @@ -0,0 +1,17 @@ +import fs from 'fs' +import path from 'path' +import http from 'http' + +const server = http.createServer do(req,res) + let html = String + + + + 'Project' + <style src='*'> + <body> + <script type="module" src='__ENTRYPOINT__'> + + res.end(html) + +imba.serve server.listen(process.env.PORT || 3000) \ No newline at end of file diff --git a/node_modules/imba/src/templates/serve-web.imba b/node_modules/imba/src/templates/serve-web.imba new file mode 100644 index 0000000..bafe5f8 --- /dev/null +++ b/node_modules/imba/src/templates/serve-web.imba @@ -0,0 +1,14 @@ +import fs from 'fs' +import path from 'path' +import http from 'http' +import index from './entry.html' + +import {serve} from 'imba/src/imba/serve.imba' + +const server = http.createServer do(req,res) + let body = index.body + if global.IMBA_HMR_PATH and body.indexOf('__hmr__.js') == -1 + body = "<script src='/__hmr__.js'></script>" + body + res.end body + +serve server.listen(Number(process.env.PORT || 3000)) diff --git a/node_modules/imba/src/templates/sharedworker.js b/node_modules/imba/src/templates/sharedworker.js new file mode 100644 index 0000000..32b0094 --- /dev/null +++ b/node_modules/imba/src/templates/sharedworker.js @@ -0,0 +1,7 @@ +import url from '__ENTRYPOINT__?worker&url'; + +export default class CustomSharedWorker extends SharedWorker { + constructor(){ + super(url); + } +} \ No newline at end of file diff --git a/node_modules/imba/src/templates/worker.js b/node_modules/imba/src/templates/worker.js new file mode 100644 index 0000000..746f479 --- /dev/null +++ b/node_modules/imba/src/templates/worker.js @@ -0,0 +1,7 @@ +import url from '__ENTRYPOINT__?worker&url'; + +export default class CustomWorker extends Worker { + constructor(){ + super(url); + } +} \ No newline at end of file diff --git a/node_modules/imba/src/templates/workerurl.js b/node_modules/imba/src/templates/workerurl.js new file mode 100644 index 0000000..1354c75 --- /dev/null +++ b/node_modules/imba/src/templates/workerurl.js @@ -0,0 +1,2 @@ +import url from '__ENTRYPOINT__?worker&url'; +export default url; \ No newline at end of file diff --git a/node_modules/imba/src/utils/identifiers.imba b/node_modules/imba/src/utils/identifiers.imba new file mode 100644 index 0000000..fbed417 --- /dev/null +++ b/node_modules/imba/src/utils/identifiers.imba @@ -0,0 +1,59 @@ + +# To avoid collisions etc with symbols we are using +# greek characters to convert special imba identifiers +# to valid js identifiers. + + +export const InternalPrefixes = { + TAG: 'τ' + FLIP: 'ω' + VALUE: 'υ' + CACHE: 'ϲ' + KEY: 'κ' + ANY: 'φ' + SYM: 'ε' + SEP: 'ι' + PRIVATE: 'Ψ' + B: 'ι' + T: 'τ' + C: 'ρ' + V: 'υ' + K: 'κ' + D: 'Δ' + H: 'θ' + EXTEND: 'Ω' +} + +export const ReservedPrefixes = new Set(Object.values(InternalPrefixes)) +export const ReservedIdentifierRegex = new RegExp("^[{Array.from(ReservedPrefixes).join('')}]",'u') +# .filter(do $3.indexOf($1) == $2).join("") + +export const ToJSMap = { + '-': 'Ξ' + '?': 'Φ' + '#': 'Ψ' + '@': 'α' +} + +const toJSregex = new RegExp("[\-\?\#\@]","gu") +const toJSreplacer = do(m) ToJSMap[m] + +export def toJSIdentifier raw + raw.replace(toJSregex,toJSreplacer) + + +export const ToImbaMap = { + 'Ξ': '-' + 'Φ': '?' + 'Ψ': '#' + 'α': '@' +} + +const toImbaRegex = new RegExp("[ΞΦΨα]","gu") +const toImbaReplacer = do(m) ToImbaMap[m] + +export def toImbaIdentifier raw + raw.replace(toImbaRegex,toImbaReplacer) + +export def toCustomTagIdentifier str + 'Γ' + toJSIdentifier(str) \ No newline at end of file diff --git a/node_modules/imba/src/utils/logger.imba b/node_modules/imba/src/utils/logger.imba new file mode 100644 index 0000000..b680c97 --- /dev/null +++ b/node_modules/imba/src/utils/logger.imba @@ -0,0 +1,215 @@ +import {performance} from 'perf_hooks' + +const ansiMap = + reset: [0, 0], + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + +const ansi = + bold: do(text) '\u001b[1m' + text + '\u001b[22m' + red: do(text) '\u001b[31m' + text + '\u001b[39m' + green: do(text) '\u001b[32m' + text + '\u001b[39m' + yellow: do(text) '\u001b[33m' + text + '\u001b[39m' + blue: do(text) '\u001b[94m' + text + '\u001b[39m' + gray: do(text) '\u001b[90m' + text + '\u001b[39m' + white: do(text) '\u001b[37m' + text + '\u001b[39m' + f: do(name,text) + let pair = ansiMap[name] + return '\u001b['+pair[0]+'m' + text + '\u001b['+pair[1]+'m' + +ansi.warn = ansi.yellow +ansi.error = ansi.red + +const notWin = process.platform !== 'win32' || process.env.CI || process.env.TERM === 'xterm-256color' + +# import ora from 'ora' + +const logSymbols = { + info: ansi.f('yellowBright',notWin ? 'ℹ' : 'i') + success: ansi.green(notWin ? '✔' : '√') + warning: ansi.yellow(notWin ? '⚠' : '!!') + error: ansi.red(notWin ? '×' : '✖') + debug: ansi.blue(notWin ? 'ℹ' : 'i') +} + +const logLevels = ['debug','info','success','warning','error','silent'] + +const addressTypeName = { + "-1": "socket" + "4": "ip4" + "6": "ip6" +} + +export def formatMarkdown str + let fmt = ansi.f + + str = str.replace(/https?\:[^\s\n\)\]]+/g) do(m) + # fmt('italic',fmt('blueBright',m)) + fmt('blueBright',m) + str = str.replace(/^[\t\s]*\>[^\n]+/gm) do(m) + # fmt('italic',fmt('blueBright',m)) + fmt('bold',m) + + str = str.replace(/\t/g,' ') + str = str.replace(/^/gm,' ') + str + +export def format str,...rest + # color markdown? + + let fmt = ansi.f + str = str.replace(/\%([\w\.]+)/g) do(m,f) + let part = rest.shift! + if f == 'markdown' + formatMarkdown(part) + + elif f == 'kb' + fmt 'dim', (part / 1000).toFixed(1) + 'kb' + elif f == 'path' or f == 'bold' + fmt('bold',part) + elif f == 'dim' + fmt('dim',part) + elif f == 'address' + let typ = addressTypeName[part.addressType] + if part.port + # what about the protocol? + fmt('blueBright',[part.address or "http://127.0.0.1",part.port].join(':')) + else + fmt('blueBright',typ) + elif f == 'ms' + fmt('yellow',Math.round(part) + 'ms') + elif f == 'd' + fmt('blueBright',part) + elif f == 'red' + fmt('redBright',part) + elif f == 'green' + fmt('green',part) + elif f == 'magenta' + fmt('magentaBright',part) + elif f == 'cyan' + fmt('cyanBright',part) + elif f == 'imba' + fmt('yellowBright',part) + elif f == 'yellow' + fmt('yellowBright',part) + elif f == 'ref' + fmt('yellowBright','#' + (part.id or part)) + elif f == 'elapsed' + rest.unshift(part) if part != undefined + let elapsed = performance.now! # Date.now! - #ctime + fmt('yellow',Math.round(elapsed) + 'ms') + elif f == 'heap' + rest.unshift(part) if part != undefined + let used = process.memoryUsage!.heapUsed / 1024 / 1024 + fmt('yellow',used.toFixed(2) + 'mb') + else + part + + return [str,...rest] + +let Spinner = null +let Instance = null + +export class Logger + + static get main + Instance ||= new self + + def constructor {prefix = null,loglevel} = {} + #ctime = Date.now! + self.prefix = prefix # ? format(...prefix)[0] : '' + # FIXME Remove IMBA_OPTIONS? + self.loglevel = loglevel or process.env.IMBA_LOGLEVEL or (global.#IMBA_OPTIONS and global.#IMBA_OPTIONS.loglevel) or 'info' + + set prefix val + #prefix = val ? format(...val)[0] : '' + + get prefix + #prefix + + def write kind,...parts + if logLevels.indexOf(kind) < logLevels.indexOf(self.loglevel) + return self + + let sym = logSymbols[kind] or kind + let [str,...rest] = format(...parts) + str = prefix + str if prefix + + if #spinner and #spinner.isSpinning + # console.log 'set text on spinner!!!' + if kind == 'success' + #spinner.clear! + console.log(sym + ' ' + str,...rest) + #spinner.frame! + + #spinner.text = str + else + console.log(sym + ' ' + str,...rest) + + def debug ...pars do write('debug',...pars) + + def log ...pars do + let [str,...rest] = format(...pars) + console.log(str,...rest) + + def info ...pars do write('info',...pars) + def warn ...pars do write('warn',...pars) + def error ...pars do write('error',...pars) + def success ...pars do write('success',...pars) + + def ts ...pars do + let now = performance.now! + let diff = #last ? (now - #last) : 0 + write('debug',...pars,ansi.blue("+{diff.toFixed(1)}ms")) + #last = now + + def spinner + return + Spinner = ora('Loading').start! + + get #spinner + Spinner + + get proxy + let fn = do(...pars) info(...pars) + fn.info = info.bind(self) + fn.log = log.bind(self) + fn.warn = warn.bind(self) + fn.error = error.bind(self) + fn.debug = debug.bind(self) + fn.success = success.bind(self) + fn.ts = ts.bind(self) + fn.logger = self + return fn + + def time label, cb + let t = Date.now! + if cb + let res = await cb() + info "{label} %ms",Date.now! - t + return res + +export default (new Logger).proxy \ No newline at end of file diff --git a/node_modules/imba/src/utils/logger.web.imba b/node_modules/imba/src/utils/logger.web.imba new file mode 100644 index 0000000..7aa235f --- /dev/null +++ b/node_modules/imba/src/utils/logger.web.imba @@ -0,0 +1,2 @@ +export default console + \ No newline at end of file diff --git a/node_modules/imba/src/utils/spec.imba b/node_modules/imba/src/utils/spec.imba new file mode 100644 index 0000000..acb3075 --- /dev/null +++ b/node_modules/imba/src/utils/spec.imba @@ -0,0 +1,485 @@ +const puppy = global.puppy + +const KeyMap = { + ctrl: 'Control' + shift: 'Shift' + meta: 'Meta' + alt: 'Alt' + left: 'ArrowLeft' + right: 'ArrowRight' + esc: 'Escape' + enter: 'Enter' + tab: 'Tab' + space: 'Space' + up: 'ArrowUp' + down: 'ArrowDown' + del: 'Backspace' + +} + +const pup = do(ns,...params) + if ns.match(/^spec/) and puppy + puppy(ns,params) + return + + # return + if puppy + await puppy(ns,params) + +class PupKeyboard + + + def type text, options = {} + await puppy('keyboard.type',[text,options]) + + def down key, options = {} + key = KeyMap[key] or key + await puppy('keyboard.down',[key,options]) + def up key, options = {} + key = KeyMap[key] or key + await puppy('keyboard.up',[key,options]) + + def press key, options = {} + key = KeyMap[key] or key + await puppy('keyboard.press',[key,options]) + + def hold key, block + key = KeyMap[key] or key + await down(key) + await block() + await up(key) + +class PupMouse + def type text, options + puppy('keyboard.type',[text,options]) + + def down x = 0, y = 0 + await move(x,y) + await puppy('mouse.down',[]) + + def move x = 0, y = 0 + await puppy('mouse.move',[x,y]) + + def up x = 0, y = 0 + await puppy('mouse.up',[]) + + def click x = 0, y = 0, o = {} + await puppy('mouse.click',[x,y,o]) + + def touch ...coords + let first = coords.shift! + await down(first[0],first[1]) + for item in coords + await move(item[0],item[1]) + await up! + +class PupPage + + def setViewport o = {} + await puppy('setViewport',[o]) + +const TERMINAL_COLOR_CODES = + bold: 1 + underline: 4 + reverse: 7 + black: 30 + red: 31 + green: 32 + yellow: 33 + blue: 34 + magenta: 35 + cyan: 36 + white: 37 + +const fmt = do(code,string) + return string.toString! if console.group + code = TERMINAL_COLOR_CODES[code] + let resetStr = "\x1B[0m" + let resetRegex = /\x1B\[0m/g + let codeRegex = /\x1B\[\d+m/g + let tagRegex = /(<\w+>|<A\d+>)|(<\/\w+>|<A\d+>)/i + let numRegex = /\d+/ + let str = ('' + string).replace(resetRegex, "{resetStr}\x1B[{code}m") # allow nesting + str = "\x1B[{code}m{str}{resetStr}" + return str + + +class SpecComponent + + def log ...params + root.console.log(*params) + + def emit ev, pars + imba.emit(self,ev,pars) + + get root + parent ? parent.root : self + + +global class Spec < SpecComponent + + get keyboard + _keyboard ||= new PupKeyboard + + get mouse + _mouse ||= new PupMouse + + get page + _page ||= new PupPage + + def click sel, trusted = yes, options = {} + if typeof trusted == 'object' + options = trusted + trusted = yes + + if puppy and trusted + # console.log "click with puppeteer!!",sel + try + await puppy('click',[sel,options]) + catch e + console.log 'error from pup click!' + else + let el = document.querySelector(sel) + el && el.click! + await tick! + + def tick commit = true + imba.commit! if commit + await imba.scheduler.promise + observer..takeRecords! + + def wait time = 100 + new Promise(do(resolve) setTimeout(resolve,time)) + + def constructor + super() + console = console + blocks = [] + assertions = [] + stack = [context = self] + tests = [] + warnings = [] + state = {info: [], mutations: [], log: [],commits: 0} + + if $web$ + observer = new MutationObserver do(muts) + context.state.mutations.push(...muts) + + self + + get fullName + "" + + def eval block, ctx + stack.push(context = ctx) + let res = block(context.state) + let after = do + stack.pop! + context = stack[stack.length - 1] + observer..takeRecords! if $web$ + self + + let err = do(e) + ctx.error = e + after! + + if res and res.then + return res.then(after,err) + else + after! + return Promise.resolve(self) + + def describe name, blk + blocks.push new SpecGroup(name, blk, self) + + def test name, blk + let inline = stack[-1] isa SpecExample + + if name isa Function + blk = name + name = inline ? "" : (context.blocks.length + 1) + + if inline + return blk() + + # if we are currently running - just push it and execute immediately + # if stack.length > 1 + # let curr = stack[-1] + # if curr isa SpecExample + # console.log "CALLING TEST INSIDE TEST!!!" + context.blocks.push new SpecExample(name, blk, context) + + def before name, blk + if name isa Function + name = 'setup' + blk = name + let blocks = context.blocks[name] ||= [] + blocks.push blk + + def eq actual, expected, options + new SpecAssert(context, actual,expected, options) + + def step i = 0 + Spec.CURRENT = self + let block = blocks[i] + return self.finish! unless block + imba.once(block,'done') do self.step(i+1) + block.run! + + def run o = {} + new Promise do(resolve,reject) + pup("spec:start",{}) + let prevInfo = console.info + if typeof o.only == 'string' + blocks = blocks.filter do $1.name.indexOf(o.only) >= 0 + + let fn = do context.state.commits++ + imba.scheduler.on('commit',fn) + observer..observe(document.body,{ + attributes: true, + childList: true, + characterData: true, + subtree: true + }) + console.log 'running spec' + console.info = do(...params) + context.state.info.push(params) + context.state.log.push(params[0]) + + imba.once(self,'done') do + observer..disconnect! + console.info = prevInfo + imba.scheduler.un('commit',fn) + resolve! + await tick! + self.step(0) + + def finish + let ok = [] + let failed = [] + + for test in tests + test.failed ? failed.push(test) : ok.push(test) + + let logs = [ + fmt('green',"{ok.length} OK") + fmt('red',"{failed.length} FAILED") + "{tests.length} TOTAL" + ] + + console.log logs.join(" | ") + + let exitCode = (failed.length == 0 ? 0 : 1) + emit('done', [exitCode]) + pup("spec:done",{ + failed: failed.length, + passed: ok.length, + warnings: warnings.length + }) + +global class SpecGroup < SpecComponent + + def constructor name, blk, parent + super() + parent = parent + name = name + blocks = [] + blk = blk + + self + + get fullName + "{parent.fullName}{name} > " + + def describe name, blk + blocks.push new SpecGroup(name, blk, self) + + def test name, blk + blocks.push new SpecExample(name, blk, self) + + def run i = 0 + start! if i == 0 + let block = blocks[i] + return finish! unless block + imba.once(block,'done') do run(i+1) + if blocks.setup + for pre in blocks.setup + await pre() + + block.run! # this is where we wan to await? + + def start + emit('start', [self]) + SPEC.eval(blk,self) if blk + + if console.group + console.group(name) + else + console.log "\n-------- {name} --------" + + def finish + console.groupEnd(name) if console.groupEnd + if parent == SPEC + cleanup! + emit('done', [self]) + + def cleanup + if $web$ + document.body.innerHTML = '' + await imba.commit! + + +global class SpecExample < SpecComponent + + def constructor name, block, parent + super() + parent = parent + evaluated = no + name = name + block = block + assertions = [] + root.tests.push(self) + state = {info: [], mutations: [], log: [], commits: 0} + self + + get fullName + "{parent.fullName}{name}" + + def run + start! + # does a block really need to run here? + try + let promise = (block ? SPEC.eval(block, self) : Promise.resolve({})) + let res = await promise + catch e + console.log "error from run!",e + error = e + evaluated = yes + finish! + + def start + emit('start') + console.group(fullName) + + def finish + failed ? fail! : pass! + let fails = assertions.filter do $1.critical + pup("spec:test", name: fullName, failed: failed, messages: fails.map(do $1.toString!), error: error && error.message ) + + for ass in assertions + if ass.failed + if ass.options.warn + pup("spec:warn",message: ass.toString!) + else + pup("spec:fail",message: ass.toString!) + console.groupEnd(fullName) + emit('done',[self]) + + def fail + # if $node$ + # logger.log("%red", "✘ {fullName}") + # else + console.log("%c✘ {fullName}", "color:orangered",state,error) + + def pass + # if $node$ + # logger.log("%green", "✔ {fullName}") + # else + console.log("%c✔ {fullName}", "color:forestgreen") + + get failed + error or assertions.some do(ass) ass.critical + + get passed + !failed! + +global class SpecAssert < SpecComponent + + def constructor parent,actual,expected,options = {} + super() + if typeof options == 'string' + options = {message: options} + + parent = parent + expected = expected + actual = actual + options = options + message = (options.message || options.warn) || "expected %2 - got %1" + parent.assertions.push(self) + self.compare(expected,actual) ? pass! : fail! + self + + def compare a,b + if a === b + return true + if a isa Array and b isa Array + return false if a.length != b.length + for item,i in a + return false unless self.compare(item,b[i]) + return JSON.stringify(a) == JSON.stringify(b) + return false + + get critical + failed && !options.warn + + def fail + failed = yes + if options.warn + root.warnings.push(self) + console.log(toString!,[expected,actual]) + self + + def pass + passed = yes + console.log(toString!,[expected,actual]) + self + + def toString + if failed and typeof message == 'string' + let str = message + str = str.replace('%1',actual) + str = str.replace('%2',expected) + return str + elif failed + "failed" + else + "ok" + +global.spec = global.SPEC = new Spec + +# global def p do console.log(*arguments) +global def describe name, blk do SPEC.context.describe(name,blk) +global def before name, blk do SPEC.before(name,blk) +# global def test name, blk do SPEC.test(name,blk) +global def test name, blk do SPEC.test(name,blk) +global def eq actual, expected, o do SPEC.eq(actual, expected, o) +global def ok actual, o do SPEC.eq(!!actual, true, o) + +global def eqcss el, match,sel,o = {} + if typeof el == 'string' + el = document.querySelector(el) + elif el isa Element and !el.parentNode + document.body.appendChild(el) + if typeof sel == 'string' + el = el.querySelector(sel) + elif typeof sel == 'number' + el = el.children[sel] + + let style = window.getComputedStyle(el) + + if typeof match == 'number' + match = {fontWeight: String(match)} + + for own k,expected of match + let real = style[k] + if expected isa RegExp + global.ok(real.match(expected),Object.assign(message: "Expected {k} {real} to match {expected}",o)) + else + global.eq(String(real),String(expected),Object.assign(message: "expected {k} == %2 (was %1)",o)) + return + +global.onerror = do(e) + console.log('page:error',{message: (e.message or e)}) + +global.onunhandledrejection = do(e) + console.log('page:error',{message: e.reason.message}) \ No newline at end of file diff --git a/node_modules/imba/src/utils/vite.imba b/node_modules/imba/src/utils/vite.imba new file mode 100644 index 0000000..b746c50 --- /dev/null +++ b/node_modules/imba/src/utils/vite.imba @@ -0,0 +1,51 @@ +import np from 'node:path' +import nfs from 'node:fs' +const {isPackageExists} = require('local-pkg') +import c from 'picocolors' + +const EXIT_CODE_RESTART = 43 +export const viteServerConfigFile = np.join(__dirname,"./vite.config.server.mjs") +export const vitestSetupPath = np.join(__dirname,"./test-setup.js") + +export def importWithFallback(bundled, user) + let pkg + try + pkg = await import(user) + catch error + pkg = await import(bundled) + pkg + +export def resolveWithFallbacks(ours, fallbacks, opts = {}) + const {ext} = opts + let pkg = ours + pkg += ".{ext}" if ext..length + fallbacks = [fallbacks] unless Array.isArray fallbacks + for fallback in fallbacks + fallback = "{ours}.{fallback}" if ext + # const userPkg = np.resolve(fallback) + if nfs.existsSync fallback + return fallback + pkg + +export def ensurePackagesInstalled(dependencies, root) + const to-install = [] + for dependency in dependencies + to-install.push dependency if !isPackageExists(dependency, {paths: [root]}) + return true if to-install.length == 0 + const promptInstall = !process.env.CI and process.stdout.isTTY + const deps = to-install.join(', ') + process.stderr.write c.red("{c.inverse(c.red(' MISSING DEP '))} Can not find dependencies '{deps}'\n\n") + if !promptInstall + return false + const prompts = await import("prompts") + const {install} = await prompts.prompt( + type: "confirm" + name: "install" + message: c.reset("Do you want to install {c.green(deps)}?")) + if install + for dependency in to-install + await (await import("@antfu/install-pkg")).installPackage(dependency, dev: true) + process.stderr.write c.yellow("\nPackages {deps} installed, re-run the command to start.\n") + process.exit EXIT_CODE_RESTART + return true + return false diff --git a/node_modules/imba/templates/default/.editorconfig b/node_modules/imba/templates/default/.editorconfig new file mode 100644 index 0000000..1180833 --- /dev/null +++ b/node_modules/imba/templates/default/.editorconfig @@ -0,0 +1,10 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true + +[*.imba] +charset = utf-8 +indent_style = tab +indent_size = 4 \ No newline at end of file diff --git a/node_modules/imba/templates/default/_gitignore b/node_modules/imba/templates/default/_gitignore new file mode 100644 index 0000000..a44058c --- /dev/null +++ b/node_modules/imba/templates/default/_gitignore @@ -0,0 +1,3 @@ +.DS_Store +node_modules +dist \ No newline at end of file diff --git a/node_modules/imba/templates/default/package.json b/node_modules/imba/templates/default/package.json new file mode 100644 index 0000000..9d96f0b --- /dev/null +++ b/node_modules/imba/templates/default/package.json @@ -0,0 +1,12 @@ +{ + "name": "imba-default-template", + "scripts": { + "dev": "imba -w src/index.html", + "start": "npm run dev", + "build": "imba build src/index.html", + "preview": "npx http-server dist" + }, + "devDependencies": { + "imba": "*" + } +} diff --git a/node_modules/imba/templates/default/src/index.html b/node_modules/imba/templates/default/src/index.html new file mode 100644 index 0000000..b21a2c1 --- /dev/null +++ b/node_modules/imba/templates/default/src/index.html @@ -0,0 +1,12 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Imba Default Template + + + + + + diff --git a/node_modules/imba/templates/default/src/main.imba b/node_modules/imba/templates/default/src/main.imba new file mode 100644 index 0000000..df79d5d --- /dev/null +++ b/node_modules/imba/templates/default/src/main.imba @@ -0,0 +1,44 @@ +global css @root ff:Arial c:white/87 bg:black/85 +global css a c:indigo5 c@hover:indigo6 +global css body m:0 d:flex ja:center h:100vh + +tag app-counter + count = 0 + "count is {count}" + + # css without a selector applies to the enclosing element + css d:inline-block user-select:none cursor:pointer fs:6 bg:gray9 + p:2.5 5 m:6 bd:1px solid transparent rd:4 tween:border-color 250ms + bc@hover:indigo5 + +tag app + + # inline styles with square brackets + + + # this css applies to nested img elements and not parents + css img h:35 p:1.5em + transition:transform 250ms, filter 250ms + @hover transform:scale(1.1) + filter:drop-shadow(0 0 4em red5) + + + + + "Imba" + + + + css p c:warm1 ws:pre + css a td:none +

+ "Check out our documentation at " + "Imba.io" + "." +

+ "Take the free Imba course on " + + "Scrimba.com" + "." + +imba.mount diff --git a/node_modules/imba/templates/express/.editorconfig b/node_modules/imba/templates/express/.editorconfig new file mode 100644 index 0000000..1180833 --- /dev/null +++ b/node_modules/imba/templates/express/.editorconfig @@ -0,0 +1,10 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true + +[*.imba] +charset = utf-8 +indent_style = tab +indent_size = 4 \ No newline at end of file diff --git a/node_modules/imba/templates/express/.nvmrc b/node_modules/imba/templates/express/.nvmrc new file mode 100644 index 0000000..6f7f377 --- /dev/null +++ b/node_modules/imba/templates/express/.nvmrc @@ -0,0 +1 @@ +v16 diff --git a/node_modules/imba/templates/express/README.md b/node_modules/imba/templates/express/README.md new file mode 100644 index 0000000..f2e4a99 --- /dev/null +++ b/node_modules/imba/templates/express/README.md @@ -0,0 +1,30 @@ +_Bootstrapped with [imba-base-template](https://github.com/imba/imba-base-template)._ + +Welcome to the Imba base template! Let's get you set up and ready to code! + +This codebase has both backend and frontend code, all written in [Imba](https://imba.io). + +**NOTE:** If all you need is a simple static website with no server logic, you can use [static hosting template](https://github.com/imba/imba-vite-template) instead. + +The files are named `server.imba` and `client.imba` for simplicity. You can call them anything you want, and organize the code any way you like. As long as your `package.json` [uses your server file](https://github.com/imba/imba-base-template/blob/main/package.json#L4-L6) and your `index.html` [uses your client file](https://github.com/imba/imba-base-template/blob/main/app/index.html#L12), it will work. + + +## Available Scripts + +In the project directory, you can run: + +### `npm dev` + +Runs the server and website in the development mode with hot reloading, linting and detailed error output in the console, and source maps. + +Open [http://localhost:3000](http://localhost:3000) to view it in the browser. When you change your code, it will live reload. + +### `npm run build` + +Builds the app for production to the `dist` folder. + +### `npm run start` + +Quickly fire up the website in production mode through NPM, like `npm run dev` but without any development settings. Will also run on [http://localhost:3000](http://localhost:3000), and can be a quick way to get started with running this site on your server. + +However, [to run Imba in production](https://imba.io/guide/run-in-production) it is recommended to use [PM2](https://github.com/Unitech/pm2) to manage the Node process(es). diff --git a/node_modules/imba/templates/express/_gitignore b/node_modules/imba/templates/express/_gitignore new file mode 100644 index 0000000..a44058c --- /dev/null +++ b/node_modules/imba/templates/express/_gitignore @@ -0,0 +1,3 @@ +.DS_Store +node_modules +dist \ No newline at end of file diff --git a/node_modules/imba/templates/express/app/assets/app.css b/node_modules/imba/templates/express/app/assets/app.css new file mode 100644 index 0000000..bcc7233 --- /dev/null +++ b/node_modules/imba/templates/express/app/assets/app.css @@ -0,0 +1,81 @@ +:root { + font-family: Inter, Avenir, Helvetica, Arial, sans-serif; + font-size: 16px; + line-height: 24px; + font-weight: 400; + + color-scheme: light dark; + color: rgba(255, 255, 255, 0.87); + background-color: #242424; + + font-synthesis: none; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -webkit-text-size-adjust: 100%; +} + +a { + font-weight: 500; + color: #646cff; + text-decoration: inherit; +} +a:hover { + color: #535bf2; +} + +body { + margin: 0; + display: flex; + place-items: center; + min-width: 320px; + min-height: 100vh; +} + +h1 { + font-size: 3.2em; + line-height: 1.1; +} + +.card { + padding: 2em; +} + +#app { + max-width: 1280px; + margin: 0 auto; + padding: 2rem; + text-align: center; +} + +button { + border-radius: 8px; + border: 1px solid transparent; + padding: 0.6em 1.2em; + font-size: 1em; + font-weight: 500; + font-family: inherit; + background-color: #1a1a1a; + cursor: pointer; + transition: border-color 0.25s; +} +button:hover { + border-color: #646cff; +} +button:focus, +button:focus-visible { + outline: 4px auto -webkit-focus-ring-color; +} + +@media (prefers-color-scheme: light) { + :root { + color: #213547; + background-color: #ffffff; + } + a:hover { + color: #747bff; + } + button { + background-color: #f9f9f9; + } +} diff --git a/node_modules/imba/templates/express/app/assets/imba.svg b/node_modules/imba/templates/express/app/assets/imba.svg new file mode 100644 index 0000000..2ebf3fc --- /dev/null +++ b/node_modules/imba/templates/express/app/assets/imba.svg @@ -0,0 +1,4 @@ + + + \ No newline at end of file diff --git a/node_modules/imba/templates/express/app/client.imba b/node_modules/imba/templates/express/app/client.imba new file mode 100644 index 0000000..6249afb --- /dev/null +++ b/node_modules/imba/templates/express/app/client.imba @@ -0,0 +1,25 @@ +import './assets/app.css' +import Counter from './lib/counter' +import logo from "./assets/imba.svg" + +# Uncomment for dark mode: +# import './dark-styles' + +tag my-first-imba-app + css .logo h:6em p:1.5em + +

+ + + + "Imba server + client" + + + + +

+ "Check out" + " Imba.io" + ", the Imba documentation website" + +imba.mount , document.getElementById('app') diff --git a/node_modules/imba/templates/express/app/dark-styles.imba b/node_modules/imba/templates/express/app/dark-styles.imba new file mode 100644 index 0000000..da6c7bd --- /dev/null +++ b/node_modules/imba/templates/express/app/dark-styles.imba @@ -0,0 +1,5 @@ +global css + @root + fs:16px lh:24px fw:400 c:white/87 + color-scheme: light dark + bgc:#242424 diff --git a/node_modules/imba/templates/express/app/index.html b/node_modules/imba/templates/express/app/index.html new file mode 100644 index 0000000..d26b0ea --- /dev/null +++ b/node_modules/imba/templates/express/app/index.html @@ -0,0 +1,14 @@ + + + + + + + Imba server + client + + + +

+ + + diff --git a/node_modules/imba/templates/express/app/lib/counter.imba b/node_modules/imba/templates/express/app/lib/counter.imba new file mode 100644 index 0000000..37c6f3a --- /dev/null +++ b/node_modules/imba/templates/express/app/lib/counter.imba @@ -0,0 +1,32 @@ +export default tag Counter < button + # This is the internal state of the tag. We're not exposing it with `prop` + # because we want to read the count from the server: + count = 0 + + # Mount runs when this tag is first attached to the DOM. + # https://imba.io/docs/components/lifecycle + def mount + # Fetch the count from the server + try + const res = await window.fetch('/count') + const data = await res.json() + count = data.count + catch e + console.error("Couldn't fetch count", e) + + def increment + # Increment the counter on the server, then update the client + try + const res = await window.fetch('/increment', { + method: 'POST' + headers: { + 'Content-Type': 'application/json' + } + body: JSON.stringify({ increment: 1 }) + }) + const data = await res.json() + count = data.count + catch e + console.error("Couldn't increment", e) + + `Count is {count}` diff --git a/node_modules/imba/templates/express/ecosystem.config.js b/node_modules/imba/templates/express/ecosystem.config.js new file mode 100644 index 0000000..fe9e517 --- /dev/null +++ b/node_modules/imba/templates/express/ecosystem.config.js @@ -0,0 +1,14 @@ +module.exports = { + apps: [ + { + script: "./dist/server.js", + }, + ], + deploy: { + production: { + ref: "origin/main", + "post-deploy": + "npm install && pm2 reload ecosystem.config.js --env production", + }, + }, +}; diff --git a/node_modules/imba/templates/express/package.json b/node_modules/imba/templates/express/package.json new file mode 100644 index 0000000..722afbc --- /dev/null +++ b/node_modules/imba/templates/express/package.json @@ -0,0 +1,22 @@ +{ + "name": "imba-base-template", + "license": "MIT", + "private": true, + "scripts": { + "start": "pm2 start ecosystem.config.js --env production", + "reload": "npm run build && pm2 reload ecosystem.config.js", + "dev": "imba -wdvsM server.imba", + "build": "imba build server.imba" + }, + "engines": { + "node": ">=16.17.0", + "npm": ">=8.15.0" + }, + "dependencies": { + "express": "*", + "imba": "*" + }, + "devDependencies": { + "@types/express": "*" + } +} diff --git a/node_modules/imba/templates/express/server.imba b/node_modules/imba/templates/express/server.imba new file mode 100644 index 0000000..aa1f606 --- /dev/null +++ b/node_modules/imba/templates/express/server.imba @@ -0,0 +1,40 @@ +import express from 'express' +import index from './app/index.html' + +# A simple state that exists until the server stops +const state = { + count: 0, +} + +# Using Imba with Express as the server is quick to set up: +const app = express() +const port = process.env.PORT or 3000 + +# Express works like usual, so we can allow JSON in the POST request: +const jsonBody = express.json({ limit: '1kb' }) + +app.post('/increment', jsonBody) do(req,res) + # A good exercise here is to add validation for the request body. + # For example, what would happen if you send a string instead of a number? + state.count += req.body.increment + + # Sending the state back to the client lets us update it right away: + res.send({ + count: state.count + }) + +app.get('/count') do(req,res) + res.send({ + count: state.count + }) + +# catch-all route that returns our index.html +app.get(/.*/) do(req,res) + # only render the html for requests that prefer an html response + unless req.accepts(['image/*', 'html']) == 'html' + return res.sendStatus(404) + + res.send(index.body) + +# Express is set up and ready to go! +imba.serve(app.listen(port)) diff --git a/node_modules/imba/templates/module/_gitignore b/node_modules/imba/templates/module/_gitignore new file mode 100644 index 0000000..0bb47d0 --- /dev/null +++ b/node_modules/imba/templates/module/_gitignore @@ -0,0 +1,27 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +!.vscode/settings.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +coverage \ No newline at end of file diff --git a/node_modules/imba/templates/module/index.html b/node_modules/imba/templates/module/index.html new file mode 100644 index 0000000..e9de4fb --- /dev/null +++ b/node_modules/imba/templates/module/index.html @@ -0,0 +1,11 @@ + + + + + + Imba Module + + + + + diff --git a/node_modules/imba/templates/module/package.json b/node_modules/imba/templates/module/package.json new file mode 100644 index 0000000..c9037c1 --- /dev/null +++ b/node_modules/imba/templates/module/package.json @@ -0,0 +1,25 @@ +{ + "name": "imba-module", + "type": "module", + "files": ["dist"], + "main": "./dist/index.umd.cjs", + "module": "./dist/index.js", + "exports": { + ".": { + "import": "./dist/index.js", + "require": "./dist/index.umd.cjs" + } + }, + "scripts": { + "dev": "vite", + "start": "vite", + "build": "vite build", + "watch": "vite build --watch", + "preview": "vite preview" + }, + "devDependencies": { + "vite": "*", + "imba": "*", + "vite-plugin-imba": "*" + } +} diff --git a/node_modules/imba/templates/module/readme.md b/node_modules/imba/templates/module/readme.md new file mode 100644 index 0000000..3722650 --- /dev/null +++ b/node_modules/imba/templates/module/readme.md @@ -0,0 +1,3 @@ +# Module Template + +See https://github.com/imba/imba.io/pull/255 for most up-to-date usage guide. diff --git a/node_modules/imba/templates/module/src/index.js b/node_modules/imba/templates/module/src/index.js new file mode 100644 index 0000000..8c406aa --- /dev/null +++ b/node_modules/imba/templates/module/src/index.js @@ -0,0 +1 @@ +import "./main.imba" diff --git a/node_modules/imba/templates/module/src/main.imba b/node_modules/imba/templates/module/src/main.imba new file mode 100644 index 0000000..93c0e34 --- /dev/null +++ b/node_modules/imba/templates/module/src/main.imba @@ -0,0 +1,16 @@ +export let state = { + count: 0 +} + +export def increment + state.count++ + +tag app + "count is {state.count}" + css d:inline-block us:none cursor:pointer fs:6 p:2.5 5 rd:2.5 + tween:box-shadow 250ms, background-color 250ms + ff:Arial c:black/87 bg:indigo4 bxs:xs + @hover bg:indigo3 bxs:lg + +if import.meta.env.MODE is 'development' + imba.mount diff --git a/node_modules/imba/templates/module/vite.config.js b/node_modules/imba/templates/module/vite.config.js new file mode 100644 index 0000000..ccee84e --- /dev/null +++ b/node_modules/imba/templates/module/vite.config.js @@ -0,0 +1,15 @@ +import { imba } from 'vite-plugin-imba'; +import { resolve } from 'path' +import { defineConfig } from 'vite'; +import { name } from './package.json' + +export default defineConfig({ + plugins: [imba()], + build: { + lib: { + name: name, + fileName: "index", + entry: resolve(__dirname, 'src/main.imba'), + }, + }, +}); diff --git a/node_modules/imba/templates/vite/index.html b/node_modules/imba/templates/vite/index.html new file mode 100644 index 0000000..52c9bb2 --- /dev/null +++ b/node_modules/imba/templates/vite/index.html @@ -0,0 +1,11 @@ + + + + + + Imba Vite Template + + + + + diff --git a/node_modules/imba/templates/vite/package.json b/node_modules/imba/templates/vite/package.json new file mode 100644 index 0000000..5c3d2ab --- /dev/null +++ b/node_modules/imba/templates/vite/package.json @@ -0,0 +1,16 @@ +{ + "name": "imba-vite-project", + "version": "0.0.0", + "type": "module", + "scripts": { + "start": "vite", + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "devDependencies": { + "vite": "*", + "imba": "*", + "vite-plugin-imba": "*" + } +} diff --git a/node_modules/imba/templates/vite/src/index.js b/node_modules/imba/templates/vite/src/index.js new file mode 100644 index 0000000..e6824ab --- /dev/null +++ b/node_modules/imba/templates/vite/src/index.js @@ -0,0 +1 @@ +import "./main.imba" \ No newline at end of file diff --git a/node_modules/imba/templates/vite/src/main.imba b/node_modules/imba/templates/vite/src/main.imba new file mode 100644 index 0000000..9ed9a1d --- /dev/null +++ b/node_modules/imba/templates/vite/src/main.imba @@ -0,0 +1,50 @@ +global css @root ff:Arial c:white/87 bg:black/85 +global css a c:indigo5 c@hover:indigo6 +global css body m:0 d:flex ja:center h:100vh + +tag app-counter + count = 0 + "Count is {count}" + + # css without a selector applies to the enclosing element + css d:inline-block user-select:none cursor:pointer fs:6 bg:gray9 + p:2.5 5 m:6 bd:1px solid transparent rd:4 tween:border-color 250ms + bc@hover:indigo5 + +tag app + + # inline styles with square brackets + + + # this css applies to nested svg elements and not parents + css img h:23 p:1.5em + transition:transform 250ms, filter 250ms + @hover transform:scale(1.1) + filter:drop-shadow(0 0 4em red5) + + + + + + css filter@hover:drop-shadow(0 0 4em white7) + + <[d:inline-block transform:rotateY(180deg)]> + + + "Imba + Vite" + + + + css p c:warm1 ws:pre + css a td:none +

+ "Check out our documentation at " + "Imba.io" + "." +

+ "Take the free Imba course on " + + "Scrimba.com" + "." + +imba.mount diff --git a/node_modules/imba/templates/vite/vite.config.js b/node_modules/imba/templates/vite/vite.config.js new file mode 100644 index 0000000..06e3bdf --- /dev/null +++ b/node_modules/imba/templates/vite/vite.config.js @@ -0,0 +1,7 @@ +import { imba } from 'vite-plugin-imba'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + base: '', + plugins: [imba()], +}); diff --git a/node_modules/imba/templates/vitest/README.md b/node_modules/imba/templates/vitest/README.md new file mode 100644 index 0000000..5a0def3 --- /dev/null +++ b/node_modules/imba/templates/vitest/README.md @@ -0,0 +1,75 @@ +[![Netlify Status](https://api.netlify.com/api/v1/badges/5aad6d39-168c-482a-9f52-3d8cd9e1c8d1/deploy-status)](https://app.netlify.com/sites/vite-imba/deploys) + +_Bootstrapped with [imba-vite-template](https://github.com/imba/imba-vite-template)._ + +Welcome to the Imba Vite template! Let's get you set up and ready to code! + +[![Deploy to Netlify Button](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/imba/imba-vite-template) + +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fimba%2Fimba-vite-template) + +## Deploy examples + +To see what it looks like when you use this template and deploy it, check out the following examples: + +- [Netlify](https://github.com/codeluggage/imba-on-netlify) +- [GitHub Pages](https://codeluggage.github.io/imba-on-github-pages/) + +## Code structure + +### `main.imba` + +In `src/main.imba` you see how [Imba styles](https://imba.io/docs/css) work. CSS is clearly scoped in Imba, so you can see [global CSS](https://imba.io/docs/css/syntax#selectors-global-selectors), tag level, and element level. + +Both [assets](https://imba.io/docs/assets) and [components](https://imba.io/docs/components/) are imported and used. Finally, the web application is started by [mounting the tag](https://imba.io/docs/tags/mounting). + +### `counter.imba` + +In `src/components/counter.imba` you see more about how [tags](https://imba.io/docs/tags), [props](https://imba.io/docs/tags#setting-properties), [state management](https://imba.io/docs/state-management) (which is usually a big, complex topic - but is very lightweight in Imba), and inheriting from the web itself (in this case, the HTML button). There's also a [Vitest in-source component test](https://vitest.dev/guide/in-source.html), showing you how this tag is meant to be used. + +### `app.css` + +You don't need to use CSS files, because of the powerful scoping of [Imba styles](https://imba.io/docs/css), but this file shows how you can get the best of both worlds. It is imported and used in `src/main.imba`. + +### `utils.imba` + +To showcase logic without any front end interactions, there's a simple example `src/utils.imba` has in-source testing and + +### `tests/` + +In `test/basic.test.imba` you see how terse and succinct the testing syntax is with Imba, using [Vitest](https://vitest.dev/). This test is in its own file with the `.test.imba` filename ending, but you can also use inline tests like in `src/components/counter.imba`. + +## Recommended IDE + +- [VS Code](https://code.visualstudio.com/). +- [Imba extension](https://marketplace.visualstudio.com/items?itemName=scrimba.vsimba) - which is automatically recommended if you open this repository in VSCode. + +## Available Scripts + +In the project directory, you can run: + +### `npm dev` + +Runs in development mode on `http://localhost:3000` with hot reloading, linting and detailed error output in the console, and source maps. + +### `npm run build` + +Builds the app for production to the `dist` folder. From here you can [deploy your app](https://imba.io/guides/deployment) to static hosting. + +### `npm run preview` + +_NOTE: Requires `npm run build` to have been run first._ + +Preview the production application from the `dist/` folder, just as it will be running on static hosting. + +### `npm test` + +Run and watch the tests. + +### `npm run test:ui` + +Run and watch the tests - and open the [Vitest UI](https://vitest.dev/guide/ui.html) + +## Notes +- This app doesn't have a server. If you need a full stack web application with server logic you can use [imba base template](https://github.com/imba/imba-base-template) or check out [Vite's backend integration guide](https://vitejs.dev/guide/backend-integration.html) +- There is a temporary `src/main.js` file that is still necessary for Vite to work correctly. You don't have to do anything with this file. And this will probably be fixed in a future version of Vite. \ No newline at end of file diff --git a/node_modules/imba/templates/vitest/_gitignore b/node_modules/imba/templates/vitest/_gitignore new file mode 100644 index 0000000..0bb47d0 --- /dev/null +++ b/node_modules/imba/templates/vitest/_gitignore @@ -0,0 +1,27 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +!.vscode/settings.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +coverage \ No newline at end of file diff --git a/node_modules/imba/templates/vitest/index.html b/node_modules/imba/templates/vitest/index.html new file mode 100644 index 0000000..529af0c --- /dev/null +++ b/node_modules/imba/templates/vitest/index.html @@ -0,0 +1,13 @@ + + + + + + + Vite + Imba + + +

+ + + diff --git a/node_modules/imba/templates/vitest/package.json b/node_modules/imba/templates/vitest/package.json new file mode 100644 index 0000000..708f0f0 --- /dev/null +++ b/node_modules/imba/templates/vitest/package.json @@ -0,0 +1,24 @@ +{ + "name": "imba-vite-project", + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "start": "vite", + "build": "vite build", + "preview": "vite preview", + "test": "vitest", + "test:ui": "vitest --ui" + }, + "devDependencies": { + "@testing-library/dom": "*", + "@vitest/ui": "*", + "jsdom": "*", + "vite": "*", + "vitest": "*", + "vitest-github-actions-reporter-temp": "*", + "@testing-library/jest-dom": "*", + "imba": "*", + "vite-plugin-imba": "*" + } +} diff --git a/node_modules/imba/templates/vitest/public/vite.svg b/node_modules/imba/templates/vitest/public/vite.svg new file mode 100644 index 0000000..e7b8dfb --- /dev/null +++ b/node_modules/imba/templates/vitest/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node_modules/imba/templates/vitest/src/app.css b/node_modules/imba/templates/vitest/src/app.css new file mode 100644 index 0000000..72d9cc9 --- /dev/null +++ b/node_modules/imba/templates/vitest/src/app.css @@ -0,0 +1,82 @@ +:root { + font-family: Inter, Avenir, Helvetica, Arial, sans-serif; + font-size: 16px; + line-height: 24px; + font-weight: 400; + + color-scheme: light dark; + color: rgba(255, 255, 255, 0.87); + background-color: #242424; + + font-synthesis: none; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -webkit-text-size-adjust: 100%; + } + + a { + font-weight: 500; + color: #646cff; + text-decoration: inherit; + } + a:hover { + color: #535bf2; + } + + body { + margin: 0; + display: flex; + place-items: center; + min-width: 320px; + min-height: 100vh; + } + + h1 { + font-size: 3.2em; + line-height: 1.1; + } + + .card { + padding: 2em; + } + + #app { + max-width: 1280px; + margin: 0 auto; + padding: 2rem; + text-align: center; + } + + button { + border-radius: 8px; + border: 1px solid transparent; + padding: 0.6em 1.2em; + font-size: 1em; + font-weight: 500; + font-family: inherit; + background-color: #1a1a1a; + cursor: pointer; + transition: border-color 0.25s; + } + button:hover { + border-color: #646cff; + } + button:focus, + button:focus-visible { + outline: 4px auto -webkit-focus-ring-color; + } + + @media (prefers-color-scheme: light) { + :root { + color: #213547; + background-color: #ffffff; + } + a:hover { + color: #747bff; + } + button { + background-color: #f9f9f9; + } + } + \ No newline at end of file diff --git a/node_modules/imba/templates/vitest/src/assets/imba.svg b/node_modules/imba/templates/vitest/src/assets/imba.svg new file mode 100644 index 0000000..0eeaba1 --- /dev/null +++ b/node_modules/imba/templates/vitest/src/assets/imba.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/node_modules/imba/templates/vitest/src/components/counter.imba b/node_modules/imba/templates/vitest/src/components/counter.imba new file mode 100644 index 0000000..594fcc7 --- /dev/null +++ b/node_modules/imba/templates/vitest/src/components/counter.imba @@ -0,0 +1,14 @@ +import {screen, waitFor} from "@testing-library/dom" + +export default tag Counter < button + prop count = 0 + `Count is {count}` + +if import.meta.vitest + it "should be a good counter", do + imba.mount + const counter = screen.getByText("Count is 0") + expect(counter).toBeTruthy! + counter.click! + waitFor do expect(screen.getByText("Count is 1")).toBeTruthy! + diff --git a/node_modules/imba/templates/vitest/src/main.imba b/node_modules/imba/templates/vitest/src/main.imba new file mode 100644 index 0000000..e4c54ad --- /dev/null +++ b/node_modules/imba/templates/vitest/src/main.imba @@ -0,0 +1,35 @@ +import './app.css' +import Counter from './components/counter.imba' +import logo from "./assets/imba.svg" + +global css + @root + fs:16px lh:24px fw:400 c:white/87 + color-scheme: light dark + bgc:#242424 + +tag app + css .logo h:6em p:1.5em + +
+ + # use svg as an svg tag + + + + + + + # use svg as an image + + + "Vite + Imba" + + +

"Check out" + " Imba.io" + ", the Imba documentation website" + "Click on the Vite and Imba logos to learn more!!!" + + +imba.mount , document.getElementById "app" diff --git a/node_modules/imba/templates/vitest/src/main.js b/node_modules/imba/templates/vitest/src/main.js new file mode 100644 index 0000000..e6824ab --- /dev/null +++ b/node_modules/imba/templates/vitest/src/main.js @@ -0,0 +1 @@ +import "./main.imba" \ No newline at end of file diff --git a/node_modules/imba/templates/vitest/src/utils.imba b/node_modules/imba/templates/vitest/src/utils.imba new file mode 100644 index 0000000..b744800 --- /dev/null +++ b/node_modules/imba/templates/vitest/src/utils.imba @@ -0,0 +1,9 @@ +export def add(...args) + return args.reduce((do(a, b) a + b), 0) + +if import.meta.vitest + const {it, expect} = import.meta.vitest + it "adds from in-source tests", do + expect(add()).toBe 0 + expect(add(1)).toBe 1 + expect(add(1, 2, 3)).toBe 6 diff --git a/node_modules/imba/templates/vitest/test/basic.test.imba b/node_modules/imba/templates/vitest/test/basic.test.imba new file mode 100644 index 0000000..3487bc3 --- /dev/null +++ b/node_modules/imba/templates/vitest/test/basic.test.imba @@ -0,0 +1,18 @@ +import add from '../src/utils.imba' + +test "add()", do + it "adds from test folder", do + expect(add(40, 2)).toBe(42) + +test "Math.sqrt()", do + expect(Math.sqrt(4)).toBe 2 + expect(Math.sqrt(144)).toBe 12 + expect(Math.sqrt(2)).toBe Math.SQRT2 + +test "JSON", do + const input = + foo: "hello" + bar: "world" + const output = JSON.stringify(input) + expect(output).toBe '{"foo":"hello","bar":"world"}' + assert.deepEqual JSON.parse(output), input, "matches original" diff --git a/node_modules/imba/templates/vitest/test/setup.imba b/node_modules/imba/templates/vitest/test/setup.imba new file mode 100644 index 0000000..0d10ed9 --- /dev/null +++ b/node_modules/imba/templates/vitest/test/setup.imba @@ -0,0 +1,6 @@ +import '@testing-library/jest-dom' +import {vi} from "vitest" +# JSDOM doesn't implement pointer event class +# see https://github.com/jsdom/jsdom/issues/2527 +class MockPointerEvent +vi.stubGlobal "PointerEvent", MockPointerEvent diff --git a/node_modules/imba/templates/vitest/tsconfig.json b/node_modules/imba/templates/vitest/tsconfig.json new file mode 100644 index 0000000..89504dd --- /dev/null +++ b/node_modules/imba/templates/vitest/tsconfig.json @@ -0,0 +1,7 @@ +{ + "compilerOptions": { + "types": [ + "vitest/importMeta" + ] + } + } \ No newline at end of file diff --git a/node_modules/imba/templates/vitest/vite.config.js b/node_modules/imba/templates/vitest/vite.config.js new file mode 100644 index 0000000..2170518 --- /dev/null +++ b/node_modules/imba/templates/vitest/vite.config.js @@ -0,0 +1,20 @@ +import { imba } from 'vite-plugin-imba'; +import { defineConfig } from 'vite'; +import GithubActionsReporter from 'vitest-github-actions-reporter-temp' + +export default defineConfig({ + plugins: [imba()], + define: { + 'import.meta.vitest': 'undefined', + }, + test: { + globals: true, + include: ["**/*.{test,spec}.{imba,js,mjs,cjs,ts,mts,cts,jsx,tsx}"], + includeSource: ['src/**/*.{imba,js,mjs,cjs,ts,mts,cts,jsx,tsx}'], + environment: "jsdom", + setupFiles: ["./test/setup.imba"], + reporters: process.env.GITHUB_ACTIONS + ? new GithubActionsReporter() + : 'default' + }, +}); diff --git a/node_modules/imba/typings/imba.d.ts b/node_modules/imba/typings/imba.d.ts new file mode 100644 index 0000000..c0510cb --- /dev/null +++ b/node_modules/imba/typings/imba.d.ts @@ -0,0 +1,708 @@ +/// +/// +/// +/// +/// +/// + +/// +/// +/// + + +interface Node { + /** + * @custom + * @summary Proxy to reference data on elements up the tree + */ + readonly Ψcontext: imba.Context; + + + /** + * @custom + * @summary Reference to the parentNode even before element has been attached + */ + readonly Ψparent: Element; +} + +interface Element { + + /** + * @idl + * @summary Default property for setting the data of an element + */ + data: any; + + /** + * @private + */ + private route__: any; + + /** + * Gives elements a stable identity inside lists + * @idl + * @deprecated Use key instead + */ + $key: any; + + /** + * Gives elements a stable identity inside lists. + * Any value (both objects and primitive values) may be used as a key. + * @idl + */ + key: any; + + + /** + * Sets whether `@hotkey` events inside of this element + * is enabled or not. If explicitly set to true, only + * `@hotkey` events inside this group will be triggered + * when this element or a child has focus. + * @summary Sets whether `@hotkey` events inside of this element + * is enabled or not + * @idl + */ + hotkeys: boolean; + + /** + * Enable transitions for when element is attached / detached + * @see[Transitions](https://imba.io/css/transitions) + * @idl + */ + ease: any; + + // itemid: any; + // itemprop: any; + // itemref: any; + // itemscope: any; + // itemtype: any; + // enterkeyhint: any; + // autofocus: any; + // autocapitalize: any; + // autocomplete: any; + // accesskey: any; + // inputmode: any; + // spellcheck: any; + // translate: any; + // is: any; + + /** + * @summary Allows for manipulation of element's class content attribute + */ + readonly flags: imba.Flags; + + /** + * Emits event + * @param event + * @param params + * @param options + * @custom + */ + emit(event: string, params?: any, options?: any): Event; + focus(options?: any): void; + blur(): void; + + // [key: string]: any; + + setAttribute(name: string, value: boolean): void; + setAttribute(name: string, value: number): void; + + addEventListener(event: string, listener: (event: Event) => void, options?: { + passive?: boolean; + once?: boolean; + capture?: boolean; + }); + + removeEventListener(event: string, listener: (event: Event) => void, options?: { + passive?: boolean; + once?: boolean; + capture?: boolean; + }); + + log(...arguments: any[]): void; +} + +interface Document { + readonly flags: imba.Flags; +} + +interface HTMLMetaElement { + property?: string; + charset?: string; +} + +interface EventListenerOptions { + passive?: boolean; + once?: boolean; +} + +interface Storage { + setItem(key: string, value: number): void; +} + +interface HTMLStyleElement { + /** + * The supplied path will be run through the imba bundler + */ + src: ImbaAsset | string; +} + + +interface SVGSVGElement { + /** + * Reference to svg asset that will be inlined + */ + src: ImbaAsset | string; +} + +declare class ΤObject { + [key: string]: any; +} + +declare class ImbaElement extends imba.Component { + +} + +/** Portal to declare window/document event handlers from + * inside custom tags. + */ +declare class Γglobal extends HTMLElement { + +} + +declare class Γteleport extends HTMLElement { + /** The element (or selector) you want to add listeners and content to */ + to: string | Element; +} + +declare class Γany extends HTMLElement { + [key: string]: any; +} + +interface HTMLElementTagNameMap { + "global": Γglobal, + "teleport": Γteleport +} + +interface ImbaAsset { + body: string; + url: string; + absPath: string; + path: string; +} + +interface Event { + detail: any; + originalEvent: Event | null; +} + +// interface Object { +// [key: string]: any; +// } + +declare namespace imba { + + interface Globals { + /** The global clearInterval() method cancels a timed, repeating action which was previously established by a call to setInterval(). */ + clearInterval(handle?: number): void; + /** The global clearTimeout() method cancels a timeout previously established by calling setTimeout(). */ + clearTimeout(handle?: number): void; + fetch(input: RequestInfo, init?: RequestInit): Promise; + queueMicrotask(callback: VoidFunction): void; + /** + * The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. + */ + setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; + /** The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires. */ + setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ + isFinite(number: number): boolean; + + /** Reference to the current window */ + readonly window: Window; + + /** Reference to the current document */ + readonly document: Document; + + /** Reference to the current document */ + readonly process: any; + + /** Dirname */ + readonly __dirname: string; + + /** Filename */ + readonly __filename: string; + + /** Real filename */ + readonly __realname: string; + + /** Reference to the global object */ + readonly global: typeof globalThis; + + /** + * Converts a string to an integer. + * @param string A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in `string`. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** Access to the global console object */ + console: Console; + } + + interface Context { + [key: string]: any; + } + + interface Flags { + /** + * + * @summary Returns true if the list contains the given token, otherwise false. + */ + contains(flag: string): boolean; + /** + * + * @summary Adds the specified token to the list. + */ + add(flag: string): void; + /** + * + * @summary Removes the specified token from the list. + */ + remove(flag: string): void; + /** + * + * @summary Toggles specified token in the list. + */ + toggle(flag: string, toggler?: any): void; + /** + * + * @summary Adds the specified token to the list + */ + incr(flag: string): number; + /** + * + * @summary Removes the specified token from the list if zero increments remain + */ + decr(flag: string): number; + } + + interface units { + /** + * Milliseconds + */ + ms: number; + + /** + * Seconds. Compiles to n * 1000 (milliseconds in one second) + */ + s: number; + + /** + * Days. Compiles to n * 60000 (milliseconds in one minute) + */ + minutes: number; + + /** + * Hours. Compiles to n * 3600000 (milliseconds in 1 hour) + */ + hours: number; + + /** + * Days. Compiles to n * 86400000 (milliseconds in one day) + */ + days: number; + + /** + * Frames per second. Compiles to 1000 / n + * Ie 60fps => 1000 / 60. + */ + fps: number; + + /** + * Pixels + */ + px: string; + } + + namespace hotkeys { + function trigger(combo: string): void; + + /** + * Format combo as readable label + */ + function humanize(combo: string, platform?: string): string; + + /** + * Format combo as html (readable keys wrapped in elements) + */ + function htmlify(combo: string, platform?: string): string; + } + + /** + * @custom + */ + class Component extends HTMLElement { + + /** + * @summary Called to update the element and their children + * @abstract + * @lifecycle + */ + render(): any; + + /** + * @summary Called on client to hydrate SSR element + * @abstract + * @lifecycle + */ + hydrate(): any; + + + /** + * @summary Called on server when stringifying a component + * @abstract + * @lifecycle + */ + dehydrate(): any; + + /** + * @summary Suspend rendering of component + * @lifecycle + */ + suspend(): this; + + /** + * @summary Unsuspend rendering of component + * @lifecycle + */ + unsuspend(): this; + + /** + * @summary Called to update element via scheduler + * @abstract + * @lifecycle + */ + tick(): any; + + /** + * @summary Tells whether the component should render + * @abstract + * @lifecycle + */ + get renderΦ(): boolean; + + /** + * @readonly + * @summary Tells whether the component is currently being mounted + * @lifecycle + */ + get mountingΦ(): boolean; + + /** + * @readonly + * @summary Tells whether the component is currently mounted in document + * @lifecycle */ + get mountedΦ(): boolean; + + /** + * @readonly + * @summary Tells whether the component has been awakened + * @lifecycle */ + get awakenedΦ(): boolean; + + /** + * @readonly + * @summary Tells whether the component has been rendered + * @lifecycle */ + get renderedΦ(): boolean; + + /** + * @readonly + * @summary Tells whether the component has been suspended + * @lifecycle */ + get suspendedΦ(): boolean; + + /** + * @readonly + * @summary Tells whether the component is currently rendering + * @lifecycle */ + get renderingΦ(): boolean; + + /** + * @readonly + * @summary Tells whether the component is scheduled to automatically render + * @lifecycle + * */ + get scheduledΦ(): boolean; + + /** + * @readonly + * @summary Tells whether the component has been hydrated on the client + * @lifecycle */ + get hydratedΦ(): boolean; + + /** + * @readonly + * @summary Tells whether the component was originally rendered on the server */ + get ssrΦ(): boolean; + + /** + * @summary Start rendering the component on every imba.commit + */ + schedule(): this; + + /** + * @summary Stop rendering the component automatically on every imba.commit + */ + unschedule(): this; + + /** + * @summary Called before any properties are set + * @lifecycle + * @abstract + */ + build(): any; + + /** + * @summary Called before any properties are set + * @lifecycle + * @abstract + */ + setup(): any; + + /** + * @summary Called when element is *first* attached to document + * @lifecycle + * @abstract + */ + awaken(): any; + + /** + * @summary Called when element is attached to document + * @lifecycle + * @abstract + */ + mount(): any; + + /** + * @summary Called when element is detached from document + * @lifecycle + * @abstract + */ + unmount(): any; + + /** + * @summary Called after render + * @lifecycle + * @abstract + */ + rendered(): any; + + + /** + Schedule the element to update itself + yes = render on events / imba.commit + no = force manual render + null / undefined = render via parent + (n)s = render every n s + (n)ms = render every n ms + (n)fps = render n times per second + + @summary Specify how / when the component should re-render + @idl + */ + autorender: boolean | number | null | `${number}ms` | `${number}s` | `${number}fps`; + } + + function setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; + function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; + function clearInterval(handle?: number): void; + function clearTimeout(handle?: number): void; + + /** + * Schedule re-render + */ + function commit(): Promise; + + /** + * Render elements in custom context + */ + function render(func: Function, context?: any): any; + + /** + * Attach an element to the dom + * @param element + * @param into + */ + function mount(element: T, into?: Element): T; + function mount(func: Function, into?: Element): Element; + + /** + * Detach element from document + * @param element + */ + function unmount(element: T): T; + + + /** + * Mark field as observable + */ + function αobservable(): void; + + /** + * Mark getter as computed + */ + function αcomputed(): void; + + /** + * Runs the method immediately after instance is initialized + * and re-runs whenever any of the referenced observables + * change. Methods marked with autorun in tag declarations + * will run immediately after mount, and automatically dispose + * when element unmounts. + */ + function αautorun(options?: any): void; + + /** + * Mark getter as lazy. It will only be evaluated once, + * and then return the resulting value forever after. + */ + function αlazy(): void; + + let colors: string[]; + + interface ImbaProcess { + on(event:string,callback:Function); + } + + let process: ImbaProcess; + + namespace types { + let events: GlobalEventHandlersEventMap; + let eventHandlers: GlobalEventHandlers; + + namespace html { + let tags: HTMLElementTagNameMap; + let events: GlobalEventHandlersEventMap; + } + + namespace svg { + let tags: SVGElementTagNameMap; + let events: SVGElementEventMap; + } + } + + let Element: Component; + + /** + * Class for scheduling + * @custom + */ + export interface Scheduler { + add(target: any, force?: boolean): void; + on(group: string, target: any): void; + un(group: string, target: any): void; + + /** Milliseconds since previous tick */ + dt: number; + } + + /** + * Reference to global scheduler + */ + let scheduler: Scheduler; + + function createIndexedFragment(...arguments: any[]): DocumentFragment; + function createKeyedFragment(...arguments: any[]): DocumentFragment; + function createLiveFragment(...arguments: any[]): DocumentFragment; + + function emit(source: any, event: string, params: any[]): void; + function listen(target: any, event: string, listener: any, path?: any): void; + function once(target: any, event: string, listener: any, path?: any): void; + function unlisten(target: any, event: string, listener: any, path?: any): void; + function indexOf(target: any, source: any): boolean; + + /** + * Start an asset-aware server + */ + function serve(target: any, options?: any): any; + + /* + Observability + TODO Complete & document types + */ + + interface Reaction { + dispose(): this; + } + + function observable(value: T): T; + + function run(callback: any): void; + function autorun(callback: any): Reaction; + + // TODO check if T responds to accessor method - if so, return the result of that type + function accessor(accessor: T,...rest:any[]): T extends {$accessor: (...args: any[]) => infer X} ? X : T; + + interface AccessorGenerator { + $accessor(target: any, key: symbol, name: string | symbol, slot: symbol, context: any); + } + + interface Accessor { + $get(target: any, key: string | symbol, name: string | symbol): any; + $set(value: any, target: any, key: string | symbol, name: string | symbol): void; + } + + + + interface Storage { + [key: string]: any; + } + + /** + * localStorage as a rich object + */ + let locals: Storage; + + /** + * sessionStorage as a rich object + */ + let session: Storage; + +} + +declare module "data:text/asset;*" { + const value: ImbaAsset; + export default value; + export const body: string; + export const url: string; + export const absPath: string; + export const path: string; +} + +declare module "imba/compiler" { + export function compile(fileName: string, options: any): any; +} + +declare module "imba" { + +} \ No newline at end of file diff --git a/node_modules/imba/typings/imba.dom.d.ts b/node_modules/imba/typings/imba.dom.d.ts new file mode 100644 index 0000000..109128f --- /dev/null +++ b/node_modules/imba/typings/imba.dom.d.ts @@ -0,0 +1,1346 @@ +interface HTMLElementAttributes { + /** Provides a hint for generating a keyboard shortcut for the current element. This attribute consists of a space-separated list of characters. The browser should use the first one that exists on the computer keyboard layout. */ + accesskey: string; + + /** + * Enable transitions for when element is attached / detached + * @see[Transitions](https://imba.io/css/transitions) + */ + ease: any; + + /** Controls whether and how text input is automatically capitalized as it is entered/edited by the user. It can have the following values: + + * `off` or `none`, no autocapitalization is applied (all letters default to lowercase) + * `on` or `sentences`, the first letter of each sentence defaults to a capital letter; all other letters default to lowercase + * `words`, the first letter of each word defaults to a capital letter; all other letters default to lowercase + * `characters`, all letters should default to uppercase */ + autocapitalize: string; + /** A space-separated list of the classes of the element. Classes allows CSS and JavaScript to select and access specific elements via the [class selectors](/en-US/docs/Web/CSS/Class_selectors) or functions like the method [`Document.getElementsByClassName()`](/en-US/docs/Web/API/Document/getElementsByClassName "returns an array-like object of all child elements which have all of the given class names."). */ + class: string; + /** An enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing. The attribute must take one of the following values: + + * `true` or the _empty string_, which indicates that the element must be editable; + * `false`, which indicates that the element must not be editable. */ + contenteditable: string; + /** The `[**id**](#attr-id)` of a [`

`](/en-US/docs/Web/HTML/Element/menu "The HTML element represents a group of commands that a user can perform or activate. This includes both list menus, which might appear across the top of a screen, as well as context menus, such as those that might appear underneath a button after it has been clicked.") to use as the contextual menu for this element. */ + contextmenu: string; + /** An enumerated attribute indicating the directionality of the element's text. It can have the following values: + + * `ltr`, which means _left to right_ and is to be used for languages that are written from the left to the right (like English); + * `rtl`, which means _right to left_ and is to be used for languages that are written from the right to the left (like Arabic); + * `auto`, which lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then it applies that directionality to the whole element. */ + dir: "ltr" | "rtl" | "auto"; + /** An enumerated attribute indicating whether the element can be dragged, using the [Drag and Drop API](/en-us/docs/DragDrop/Drag_and_Drop). It can have the following values: + + * `true`, which indicates that the element may be dragged + * `false`, which indicates that the element may not be dragged. */ + draggable: "true" | "false"; + /** An enumerated attribute indicating what types of content can be dropped on an element, using the [Drag and Drop API](/en-US/docs/DragDrop/Drag_and_Drop). It can have the following values: + + * `copy`, which indicates that dropping will create a copy of the element that was dragged + * `move`, which indicates that the element that was dragged will be moved to this new location. + * `link`, will create a link to the dragged data. */ + dropzone: string; + /** Used to transitively export shadow parts from a nested shadow tree into a containing light tree. */ + exportparts: string; + /** A Boolean attribute indicates that the element is not yet, or is no longer, _relevant_. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. The browser won't render such elements. This attribute must not be used to hide content that could legitimately be shown. */ + hidden: string; + /** Defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS). */ + id: string; + /** Provides a hint to browsers as to the type of virtual keyboard configuration to use when editing this element or its contents. Used primarily on [``](/en-US/docs/Web/HTML/Element/input "The HTML element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent.") elements, but is usable on any element while in `[contenteditable](/en-US/docs/Web/HTML/Global_attributes#attr-contenteditable)` mode. */ + inputmode: string; + /** Allows you to specify that a standard HTML element should behave like a registered custom built-in element (see [Using custom elements](/en-US/docs/Web/Web_Components/Using_custom_elements) for more details). */ + is: string; + /** The unique, global identifier of an item. */ + itemid: string; + /** Used to add properties to an item. Every HTML element may have an `itemprop` attribute specified, where an `itemprop` consists of a name and value pair. */ + itemprop: string; + /** Properties that are not descendants of an element with the `itemscope` attribute can be associated with the item using an `itemref`. It provides a list of element ids (not `itemid`s) with additional properties elsewhere in the document. */ + itemref: string; + /** `itemscope` (usually) works along with `[itemtype](/en-US/docs/Web/HTML/Global_attributes#attr-itemtype)` to specify that the HTML contained in a block is about a particular item. `itemscope` creates the Item and defines the scope of the `itemtype` associated with it. `itemtype` is a valid URL of a vocabulary (such as [schema.org](https://schema.org/)) that describes the item and its properties context. */ + itemscope: string; + /** Specifies the URL of the vocabulary that will be used to define `itemprop`s (item properties) in the data structure. `[itemscope](/en-US/docs/Web/HTML/Global_attributes#attr-itemscope)` is used to set the scope of where in the data structure the vocabulary set by `itemtype` will be active. */ + itemtype: string; + /** Helps define the language of an element: the language that non-editable elements are in, or the language that editable elements should be written in by the user. The attribute contains one “language tag” (made of hyphen-separated “language subtags”) in the format defined in [_Tags for Identifying Languages (BCP47)_](https://www.ietf.org/rfc/bcp/bcp47.txt). [**xml:lang**](#attr-xml:lang) has priority over it. */ + lang: string; + /** A space-separated list of the part names of the element. Part names allows CSS to select and style specific elements in a shadow tree via the [`::part`](/en-US/docs/Web/CSS/::part "The ::part CSS pseudo-element represents any element within a shadow tree that has a matching part attribute.") pseudo-element. */ + part: string; + /** */ + role: "alert" | "alertdialog" | "button" | "checkbox" | "dialog" | "gridcell" | "link" | "log" | "marquee" | "menuitem" | "menuitemcheckbox" | "menuitemradio" | "option" | "progressbar" | "radio" | "scrollbar" | "searchbox" | "slider" | "spinbutton" | "status" | "switch" | "tab" | "tabpanel" | "textbox" | "timer" | "tooltip" | "treeitem" | "combobox" | "grid" | "listbox" | "menu" | "menubar" | "radiogroup" | "tablist" | "tree" | "treegrid" | "application" | "article" | "cell" | "columnheader" | "definition" | "directory" | "document" | "feed" | "figure" | "group" | "heading" | "img" | "list" | "listitem" | "math" | "none" | "note" | "presentation" | "region" | "row" | "rowgroup" | "rowheader" | "separator" | "table" | "term" | "text" | "toolbar" | "banner" | "complementary" | "contentinfo" | "form" | "main" | "navigation" | "region" | "search" | "doc-abstract" | "doc-acknowledgments" | "doc-afterword" | "doc-appendix" | "doc-backlink" | "doc-biblioentry" | "doc-bibliography" | "doc-biblioref" | "doc-chapter" | "doc-colophon" | "doc-conclusion" | "doc-cover" | "doc-credit" | "doc-credits" | "doc-dedication" | "doc-endnote" | "doc-endnotes" | "doc-epigraph" | "doc-epilogue" | "doc-errata" | "doc-example" | "doc-footnote" | "doc-foreword" | "doc-glossary" | "doc-glossref" | "doc-index" | "doc-introduction" | "doc-noteref" | "doc-notice" | "doc-pagebreak" | "doc-pagelist" | "doc-part" | "doc-preface" | "doc-prologue" | "doc-pullquote" | "doc-qna" | "doc-subtitle" | "doc-tip" | "doc-toc"; + /** Assigns a slot in a [shadow DOM](/en-US/docs/Web/Web_Components/Shadow_DOM) shadow tree to an element: An element with a `slot` attribute is assigned to the slot created by the [``](/en-US/docs/Web/HTML/Element/slot "The HTML element—part of the Web Components technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together.") element whose `[name](/en-US/docs/Web/HTML/Element/slot#attr-name)` attribute's value matches that `slot` attribute's value. */ + slot: string; + /** An enumerated attribute defines whether the element may be checked for spelling errors. It may have the following values: + + * `true`, which indicates that the element should be, if possible, checked for spelling errors; + * `false`, which indicates that the element should not be checked for spelling errors. */ + spellcheck: "true" | "false"; + /** Contains [CSS](/en-US/docs/Web/CSS) styling declarations to be applied to the element. Note that it is recommended for styles to be defined in a separate file or files. This attribute and the [`' + * ) + * document.type //=> 'document' + * document.nodes.length //=> 2 + * ``` + */ +export default class Document extends Container { + type: 'document' + parent: undefined + + constructor(defaults?: DocumentProps) + + /** + * Returns a `Result` instance representing the document’s CSS roots. + * + * ```js + * const root1 = postcss.parse(css1, { from: 'a.css' }) + * const root2 = postcss.parse(css2, { from: 'b.css' }) + * const document = postcss.document() + * document.append(root1) + * document.append(root2) + * const result = document.toResult({ to: 'all.css', map: true }) + * ``` + * + * @param opts Options. + * @return Result with current document’s CSS. + */ + toResult(options?: ProcessOptions): Result +} diff --git a/node_modules/postcss/lib/document.js b/node_modules/postcss/lib/document.js new file mode 100644 index 0000000..4468991 --- /dev/null +++ b/node_modules/postcss/lib/document.js @@ -0,0 +1,33 @@ +'use strict' + +let Container = require('./container') + +let LazyResult, Processor + +class Document extends Container { + constructor(defaults) { + // type needs to be passed to super, otherwise child roots won't be normalized correctly + super({ type: 'document', ...defaults }) + + if (!this.nodes) { + this.nodes = [] + } + } + + toResult(opts = {}) { + let lazy = new LazyResult(new Processor(), this, opts) + + return lazy.stringify() + } +} + +Document.registerLazyResult = dependant => { + LazyResult = dependant +} + +Document.registerProcessor = dependant => { + Processor = dependant +} + +module.exports = Document +Document.default = Document diff --git a/node_modules/postcss/lib/fromJSON.d.ts b/node_modules/postcss/lib/fromJSON.d.ts new file mode 100644 index 0000000..13b169c --- /dev/null +++ b/node_modules/postcss/lib/fromJSON.d.ts @@ -0,0 +1,5 @@ +import { JSONHydrator } from './postcss.js' + +declare const fromJSON: JSONHydrator + +export default fromJSON diff --git a/node_modules/postcss/lib/fromJSON.js b/node_modules/postcss/lib/fromJSON.js new file mode 100644 index 0000000..09f2b89 --- /dev/null +++ b/node_modules/postcss/lib/fromJSON.js @@ -0,0 +1,54 @@ +'use strict' + +let Declaration = require('./declaration') +let PreviousMap = require('./previous-map') +let Comment = require('./comment') +let AtRule = require('./at-rule') +let Input = require('./input') +let Root = require('./root') +let Rule = require('./rule') + +function fromJSON(json, inputs) { + if (Array.isArray(json)) return json.map(n => fromJSON(n)) + + let { inputs: ownInputs, ...defaults } = json + if (ownInputs) { + inputs = [] + for (let input of ownInputs) { + let inputHydrated = { ...input, __proto__: Input.prototype } + if (inputHydrated.map) { + inputHydrated.map = { + ...inputHydrated.map, + __proto__: PreviousMap.prototype + } + } + inputs.push(inputHydrated) + } + } + if (defaults.nodes) { + defaults.nodes = json.nodes.map(n => fromJSON(n, inputs)) + } + if (defaults.source) { + let { inputId, ...source } = defaults.source + defaults.source = source + if (inputId != null) { + defaults.source.input = inputs[inputId] + } + } + if (defaults.type === 'root') { + return new Root(defaults) + } else if (defaults.type === 'decl') { + return new Declaration(defaults) + } else if (defaults.type === 'rule') { + return new Rule(defaults) + } else if (defaults.type === 'comment') { + return new Comment(defaults) + } else if (defaults.type === 'atrule') { + return new AtRule(defaults) + } else { + throw new Error('Unknown node type: ' + json.type) + } +} + +module.exports = fromJSON +fromJSON.default = fromJSON diff --git a/node_modules/postcss/lib/input.d.ts b/node_modules/postcss/lib/input.d.ts new file mode 100644 index 0000000..48c904b --- /dev/null +++ b/node_modules/postcss/lib/input.d.ts @@ -0,0 +1,185 @@ +import { CssSyntaxError, ProcessOptions } from './postcss.js' +import PreviousMap from './previous-map.js' + +export interface FilePosition { + /** + * URL for the source file. + */ + url: string + + /** + * Absolute path to the source file. + */ + file?: string + + /** + * Line of inclusive start position in source file. + */ + line: number + + /** + * Column of inclusive start position in source file. + */ + column: number + + /** + * Line of exclusive end position in source file. + */ + endLine?: number + + /** + * Column of exclusive end position in source file. + */ + endColumn?: number + + /** + * Source code. + */ + source?: string +} + +/** + * Represents the source CSS. + * + * ```js + * const root = postcss.parse(css, { from: file }) + * const input = root.source.input + * ``` + */ +export default class Input { + /** + * Input CSS source. + * + * ```js + * const input = postcss.parse('a{}', { from: file }).input + * input.css //=> "a{}" + * ``` + */ + css: string + + /** + * The input source map passed from a compilation step before PostCSS + * (for example, from Sass compiler). + * + * ```js + * root.source.input.map.consumer().sources //=> ['a.sass'] + * ``` + */ + map: PreviousMap + + /** + * The absolute path to the CSS source file defined + * with the `from` option. + * + * ```js + * const root = postcss.parse(css, { from: 'a.css' }) + * root.source.input.file //=> '/home/ai/a.css' + * ``` + */ + file?: string + + /** + * The unique ID of the CSS source. It will be created if `from` option + * is not provided (because PostCSS does not know the file path). + * + * ```js + * const root = postcss.parse(css) + * root.source.input.file //=> undefined + * root.source.input.id //=> "" + * ``` + */ + id?: string + + /** + * The flag to indicate whether or not the source code has Unicode BOM. + */ + hasBOM: boolean + + /** + * @param css Input CSS source. + * @param opts Process options. + */ + constructor(css: string, opts?: ProcessOptions) + + /** + * The CSS source identifier. Contains `Input#file` if the user + * set the `from` option, or `Input#id` if they did not. + * + * ```js + * const root = postcss.parse(css, { from: 'a.css' }) + * root.source.input.from //=> "/home/ai/a.css" + * + * const root = postcss.parse(css) + * root.source.input.from //=> "" + * ``` + */ + get from(): string + + /** + * Reads the input source map and returns a symbol position + * in the input source (e.g., in a Sass file that was compiled + * to CSS before being passed to PostCSS). Optionally takes an + * end position, exclusive. + * + * ```js + * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 } + * root.source.input.origin(1, 1, 1, 4) + * //=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 } + * ``` + * + * @param line Line for inclusive start position in input CSS. + * @param column Column for inclusive start position in input CSS. + * @param endLine Line for exclusive end position in input CSS. + * @param endColumn Column for exclusive end position in input CSS. + * + * @return Position in input source. + */ + origin( + line: number, + column: number, + endLine?: number, + endColumn?: number + ): FilePosition | false + + /** + * Converts source offset to line and column. + * + * @param offset Source offset. + */ + fromOffset(offset: number): { line: number; col: number } | null + + /** + * Returns `CssSyntaxError` with information about the error and its position. + */ + error( + message: string, + line: number, + column: number, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + error( + message: string, + offset: number, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + error( + message: string, + start: + | { + offset: number + } + | { + line: number + column: number + }, + end: + | { + offset: number + } + | { + line: number + column: number + }, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError +} diff --git a/node_modules/postcss/lib/input.js b/node_modules/postcss/lib/input.js new file mode 100644 index 0000000..a1c52c7 --- /dev/null +++ b/node_modules/postcss/lib/input.js @@ -0,0 +1,248 @@ +'use strict' + +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { fileURLToPath, pathToFileURL } = require('url') +let { resolve, isAbsolute } = require('path') +let { nanoid } = require('nanoid/non-secure') + +let terminalHighlight = require('./terminal-highlight') +let CssSyntaxError = require('./css-syntax-error') +let PreviousMap = require('./previous-map') + +let fromOffsetCache = Symbol('fromOffsetCache') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(resolve && isAbsolute) + +class Input { + constructor(css, opts = {}) { + if ( + css === null || + typeof css === 'undefined' || + (typeof css === 'object' && !css.toString) + ) { + throw new Error(`PostCSS received ${css} instead of CSS string`) + } + + this.css = css.toString() + + if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { + this.hasBOM = true + this.css = this.css.slice(1) + } else { + this.hasBOM = false + } + + if (opts.from) { + if ( + !pathAvailable || + /^\w+:\/\//.test(opts.from) || + isAbsolute(opts.from) + ) { + this.file = opts.from + } else { + this.file = resolve(opts.from) + } + } + + if (pathAvailable && sourceMapAvailable) { + let map = new PreviousMap(this.css, opts) + if (map.text) { + this.map = map + let file = map.consumer().file + if (!this.file && file) this.file = this.mapResolve(file) + } + } + + if (!this.file) { + this.id = '' + } + if (this.map) this.map.file = this.from + } + + fromOffset(offset) { + let lastLine, lineToIndex + if (!this[fromOffsetCache]) { + let lines = this.css.split('\n') + lineToIndex = new Array(lines.length) + let prevIndex = 0 + + for (let i = 0, l = lines.length; i < l; i++) { + lineToIndex[i] = prevIndex + prevIndex += lines[i].length + 1 + } + + this[fromOffsetCache] = lineToIndex + } else { + lineToIndex = this[fromOffsetCache] + } + lastLine = lineToIndex[lineToIndex.length - 1] + + let min = 0 + if (offset >= lastLine) { + min = lineToIndex.length - 1 + } else { + let max = lineToIndex.length - 2 + let mid + while (min < max) { + mid = min + ((max - min) >> 1) + if (offset < lineToIndex[mid]) { + max = mid - 1 + } else if (offset >= lineToIndex[mid + 1]) { + min = mid + 1 + } else { + min = mid + break + } + } + } + return { + line: min + 1, + col: offset - lineToIndex[min] + 1 + } + } + + error(message, line, column, opts = {}) { + let result, endLine, endColumn + + if (line && typeof line === 'object') { + let start = line + let end = column + if (typeof start.offset === 'number') { + let pos = this.fromOffset(start.offset) + line = pos.line + column = pos.col + } else { + line = start.line + column = start.column + } + if (typeof end.offset === 'number') { + let pos = this.fromOffset(end.offset) + endLine = pos.line + endColumn = pos.col + } else { + endLine = end.line + endColumn = end.column + } + } else if (!column) { + let pos = this.fromOffset(line) + line = pos.line + column = pos.col + } + + let origin = this.origin(line, column, endLine, endColumn) + if (origin) { + result = new CssSyntaxError( + message, + origin.endLine === undefined + ? origin.line + : { line: origin.line, column: origin.column }, + origin.endLine === undefined + ? origin.column + : { line: origin.endLine, column: origin.endColumn }, + origin.source, + origin.file, + opts.plugin + ) + } else { + result = new CssSyntaxError( + message, + endLine === undefined ? line : { line, column }, + endLine === undefined ? column : { line: endLine, column: endColumn }, + this.css, + this.file, + opts.plugin + ) + } + + result.input = { line, column, endLine, endColumn, source: this.css } + if (this.file) { + if (pathToFileURL) { + result.input.url = pathToFileURL(this.file).toString() + } + result.input.file = this.file + } + + return result + } + + origin(line, column, endLine, endColumn) { + if (!this.map) return false + let consumer = this.map.consumer() + + let from = consumer.originalPositionFor({ line, column }) + if (!from.source) return false + + let to + if (typeof endLine === 'number') { + to = consumer.originalPositionFor({ line: endLine, column: endColumn }) + } + + let fromUrl + + if (isAbsolute(from.source)) { + fromUrl = pathToFileURL(from.source) + } else { + fromUrl = new URL( + from.source, + this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile) + ) + } + + let result = { + url: fromUrl.toString(), + line: from.line, + column: from.column, + endLine: to && to.line, + endColumn: to && to.column + } + + if (fromUrl.protocol === 'file:') { + if (fileURLToPath) { + result.file = fileURLToPath(fromUrl) + } else { + /* c8 ignore next 2 */ + throw new Error(`file: protocol is not available in this PostCSS build`) + } + } + + let source = consumer.sourceContentFor(from.source) + if (source) result.source = source + + return result + } + + mapResolve(file) { + if (/^\w+:\/\//.test(file)) { + return file + } + return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file) + } + + get from() { + return this.file || this.id + } + + toJSON() { + let json = {} + for (let name of ['hasBOM', 'css', 'file', 'id']) { + if (this[name] != null) { + json[name] = this[name] + } + } + if (this.map) { + json.map = { ...this.map } + if (json.map.consumerCache) { + json.map.consumerCache = undefined + } + } + return json + } +} + +module.exports = Input +Input.default = Input + +if (terminalHighlight && terminalHighlight.registerInput) { + terminalHighlight.registerInput(Input) +} diff --git a/node_modules/postcss/lib/lazy-result.d.ts b/node_modules/postcss/lib/lazy-result.d.ts new file mode 100644 index 0000000..a514234 --- /dev/null +++ b/node_modules/postcss/lib/lazy-result.d.ts @@ -0,0 +1,176 @@ +import Result, { Message, ResultOptions } from './result.js' +import { SourceMap } from './postcss.js' +import Processor from './processor.js' +import Warning from './warning.js' +import Root from './root.js' + +/** + * A Promise proxy for the result of PostCSS transformations. + * + * A `LazyResult` instance is returned by `Processor#process`. + * + * ```js + * const lazy = postcss([autoprefixer]).process(css) + * ``` + */ +export default class LazyResult implements PromiseLike { + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls `onFulfilled` with a Result instance. If a plugin throws + * an error, the `onRejected` callback will be executed. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css, { from: cssPath }).then(result => { + * console.log(result.css) + * }) + * ``` + */ + then: Promise['then'] + + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls onRejected for each error thrown in any plugin. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css).then(result => { + * console.log(result.css) + * }).catch(error => { + * console.error(error) + * }) + * ``` + */ + catch: Promise['catch'] + + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls onFinally on any error or when all plugins will finish work. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css).finally(() => { + * console.log('processing ended') + * }) + * ``` + */ + finally: Promise['finally'] + + /** + * @param processor Processor used for this transformation. + * @param css CSS to parse and transform. + * @param opts Options from the `Processor#process` or `Root#toResult`. + */ + constructor(processor: Processor, css: string, opts: ResultOptions) + + /** + * Returns the default string description of an object. + * Required to implement the Promise interface. + */ + get [Symbol.toStringTag](): string + + /** + * Returns a `Processor` instance, which will be used + * for CSS transformations. + */ + get processor(): Processor + + /** + * Options from the `Processor#process` call. + */ + get opts(): ResultOptions + + /** + * Processes input CSS through synchronous plugins, converts `Root` + * to a CSS string and returns `Result#css`. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get css(): string + + /** + * An alias for the `css` property. Use it with syntaxes + * that generate non-CSS output. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get content(): string + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#map`. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get map(): SourceMap + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#root`. + * + * This property will only work with synchronous plugins. If the processor + * contains any asynchronous plugins it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get root(): Root + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#messages`. + * + * This property will only work with synchronous plugins. If the processor + * contains any asynchronous plugins it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get messages(): Message[] + + /** + * Processes input CSS through synchronous plugins + * and calls `Result#warnings`. + * + * @return Warnings from plugins. + */ + warnings(): Warning[] + + /** + * Alias for the `LazyResult#css` property. + * + * ```js + * lazy + '' === lazy.css + * ``` + * + * @return Output CSS. + */ + toString(): string + + /** + * Run plugin in sync way and return `Result`. + * + * @return Result with output content. + */ + sync(): Result + + /** + * Run plugin in async way and return `Result`. + * + * @return Result with output content. + */ + async(): Promise +} diff --git a/node_modules/postcss/lib/lazy-result.js b/node_modules/postcss/lib/lazy-result.js new file mode 100644 index 0000000..584a95d --- /dev/null +++ b/node_modules/postcss/lib/lazy-result.js @@ -0,0 +1,550 @@ +'use strict' + +let { isClean, my } = require('./symbols') +let MapGenerator = require('./map-generator') +let stringify = require('./stringify') +let Container = require('./container') +let Document = require('./document') +let warnOnce = require('./warn-once') +let Result = require('./result') +let parse = require('./parse') +let Root = require('./root') + +const TYPE_TO_CLASS_NAME = { + document: 'Document', + root: 'Root', + atrule: 'AtRule', + rule: 'Rule', + decl: 'Declaration', + comment: 'Comment' +} + +const PLUGIN_PROPS = { + postcssPlugin: true, + prepare: true, + Once: true, + Document: true, + Root: true, + Declaration: true, + Rule: true, + AtRule: true, + Comment: true, + DeclarationExit: true, + RuleExit: true, + AtRuleExit: true, + CommentExit: true, + RootExit: true, + DocumentExit: true, + OnceExit: true +} + +const NOT_VISITORS = { + postcssPlugin: true, + prepare: true, + Once: true +} + +const CHILDREN = 0 + +function isPromise(obj) { + return typeof obj === 'object' && typeof obj.then === 'function' +} + +function getEvents(node) { + let key = false + let type = TYPE_TO_CLASS_NAME[node.type] + if (node.type === 'decl') { + key = node.prop.toLowerCase() + } else if (node.type === 'atrule') { + key = node.name.toLowerCase() + } + + if (key && node.append) { + return [ + type, + type + '-' + key, + CHILDREN, + type + 'Exit', + type + 'Exit-' + key + ] + } else if (key) { + return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key] + } else if (node.append) { + return [type, CHILDREN, type + 'Exit'] + } else { + return [type, type + 'Exit'] + } +} + +function toStack(node) { + let events + if (node.type === 'document') { + events = ['Document', CHILDREN, 'DocumentExit'] + } else if (node.type === 'root') { + events = ['Root', CHILDREN, 'RootExit'] + } else { + events = getEvents(node) + } + + return { + node, + events, + eventIndex: 0, + visitors: [], + visitorIndex: 0, + iterator: 0 + } +} + +function cleanMarks(node) { + node[isClean] = false + if (node.nodes) node.nodes.forEach(i => cleanMarks(i)) + return node +} + +let postcss = {} + +class LazyResult { + constructor(processor, css, opts) { + this.stringified = false + this.processed = false + + let root + if ( + typeof css === 'object' && + css !== null && + (css.type === 'root' || css.type === 'document') + ) { + root = cleanMarks(css) + } else if (css instanceof LazyResult || css instanceof Result) { + root = cleanMarks(css.root) + if (css.map) { + if (typeof opts.map === 'undefined') opts.map = {} + if (!opts.map.inline) opts.map.inline = false + opts.map.prev = css.map + } + } else { + let parser = parse + if (opts.syntax) parser = opts.syntax.parse + if (opts.parser) parser = opts.parser + if (parser.parse) parser = parser.parse + + try { + root = parser(css, opts) + } catch (error) { + this.processed = true + this.error = error + } + + if (root && !root[my]) { + /* c8 ignore next 2 */ + Container.rebuild(root) + } + } + + this.result = new Result(processor, root, opts) + this.helpers = { ...postcss, result: this.result, postcss } + this.plugins = this.processor.plugins.map(plugin => { + if (typeof plugin === 'object' && plugin.prepare) { + return { ...plugin, ...plugin.prepare(this.result) } + } else { + return plugin + } + }) + } + + get [Symbol.toStringTag]() { + return 'LazyResult' + } + + get processor() { + return this.result.processor + } + + get opts() { + return this.result.opts + } + + get css() { + return this.stringify().css + } + + get content() { + return this.stringify().content + } + + get map() { + return this.stringify().map + } + + get root() { + return this.sync().root + } + + get messages() { + return this.sync().messages + } + + warnings() { + return this.sync().warnings() + } + + toString() { + return this.css + } + + then(onFulfilled, onRejected) { + if (process.env.NODE_ENV !== 'production') { + if (!('from' in this.opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ) + } + } + return this.async().then(onFulfilled, onRejected) + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + async() { + if (this.error) return Promise.reject(this.error) + if (this.processed) return Promise.resolve(this.result) + if (!this.processing) { + this.processing = this.runAsync() + } + return this.processing + } + + sync() { + if (this.error) throw this.error + if (this.processed) return this.result + this.processed = true + + if (this.processing) { + throw this.getAsyncError() + } + + for (let plugin of this.plugins) { + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + this.walkSync(root) + } + if (this.listeners.OnceExit) { + if (root.type === 'document') { + for (let subRoot of root.nodes) { + this.visitSync(this.listeners.OnceExit, subRoot) + } + } else { + this.visitSync(this.listeners.OnceExit, root) + } + } + } + + return this.result + } + + stringify() { + if (this.error) throw this.error + if (this.stringified) return this.result + this.stringified = true + + this.sync() + + let opts = this.result.opts + let str = stringify + if (opts.syntax) str = opts.syntax.stringify + if (opts.stringifier) str = opts.stringifier + if (str.stringify) str = str.stringify + + let map = new MapGenerator(str, this.result.root, this.result.opts) + let data = map.generate() + this.result.css = data[0] + this.result.map = data[1] + + return this.result + } + + walkSync(node) { + node[isClean] = true + let events = getEvents(node) + for (let event of events) { + if (event === CHILDREN) { + if (node.nodes) { + node.each(child => { + if (!child[isClean]) this.walkSync(child) + }) + } + } else { + let visitors = this.listeners[event] + if (visitors) { + if (this.visitSync(visitors, node.toProxy())) return + } + } + } + } + + visitSync(visitors, node) { + for (let [plugin, visitor] of visitors) { + this.result.lastPlugin = plugin + let promise + try { + promise = visitor(node, this.helpers) + } catch (e) { + throw this.handleError(e, node.proxyOf) + } + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + return true + } + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + } + + runOnRoot(plugin) { + this.result.lastPlugin = plugin + try { + if (typeof plugin === 'object' && plugin.Once) { + if (this.result.root.type === 'document') { + let roots = this.result.root.nodes.map(root => + plugin.Once(root, this.helpers) + ) + + if (isPromise(roots[0])) { + return Promise.all(roots) + } + + return roots + } + + return plugin.Once(this.result.root, this.helpers) + } else if (typeof plugin === 'function') { + return plugin(this.result.root, this.result) + } + } catch (error) { + throw this.handleError(error) + } + } + + getAsyncError() { + throw new Error('Use process(css).then(cb) to work with async plugins') + } + + handleError(error, node) { + let plugin = this.result.lastPlugin + try { + if (node) node.addToError(error) + this.error = error + if (error.name === 'CssSyntaxError' && !error.plugin) { + error.plugin = plugin.postcssPlugin + error.setMessage() + } else if (plugin.postcssVersion) { + if (process.env.NODE_ENV !== 'production') { + let pluginName = plugin.postcssPlugin + let pluginVer = plugin.postcssVersion + let runtimeVer = this.result.processor.version + let a = pluginVer.split('.') + let b = runtimeVer.split('.') + + if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { + // eslint-disable-next-line no-console + console.error( + 'Unknown error from PostCSS plugin. Your current PostCSS ' + + 'version is ' + + runtimeVer + + ', but ' + + pluginName + + ' uses ' + + pluginVer + + '. Perhaps this is the source of the error below.' + ) + } + } + } + } catch (err) { + /* c8 ignore next 3 */ + // eslint-disable-next-line no-console + if (console && console.error) console.error(err) + } + return error + } + + async runAsync() { + this.plugin = 0 + for (let i = 0; i < this.plugins.length; i++) { + let plugin = this.plugins[i] + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + try { + await promise + } catch (error) { + throw this.handleError(error) + } + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + let stack = [toStack(root)] + while (stack.length > 0) { + let promise = this.visitTick(stack) + if (isPromise(promise)) { + try { + await promise + } catch (e) { + let node = stack[stack.length - 1].node + throw this.handleError(e, node) + } + } + } + } + + if (this.listeners.OnceExit) { + for (let [plugin, visitor] of this.listeners.OnceExit) { + this.result.lastPlugin = plugin + try { + if (root.type === 'document') { + let roots = root.nodes.map(subRoot => + visitor(subRoot, this.helpers) + ) + + await Promise.all(roots) + } else { + await visitor(root, this.helpers) + } + } catch (e) { + throw this.handleError(e) + } + } + } + } + + this.processed = true + return this.stringify() + } + + prepareVisitors() { + this.listeners = {} + let add = (plugin, type, cb) => { + if (!this.listeners[type]) this.listeners[type] = [] + this.listeners[type].push([plugin, cb]) + } + for (let plugin of this.plugins) { + if (typeof plugin === 'object') { + for (let event in plugin) { + if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { + throw new Error( + `Unknown event ${event} in ${plugin.postcssPlugin}. ` + + `Try to update PostCSS (${this.processor.version} now).` + ) + } + if (!NOT_VISITORS[event]) { + if (typeof plugin[event] === 'object') { + for (let filter in plugin[event]) { + if (filter === '*') { + add(plugin, event, plugin[event][filter]) + } else { + add( + plugin, + event + '-' + filter.toLowerCase(), + plugin[event][filter] + ) + } + } + } else if (typeof plugin[event] === 'function') { + add(plugin, event, plugin[event]) + } + } + } + } + } + this.hasListener = Object.keys(this.listeners).length > 0 + } + + visitTick(stack) { + let visit = stack[stack.length - 1] + let { node, visitors } = visit + + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + stack.pop() + return + } + + if (visitors.length > 0 && visit.visitorIndex < visitors.length) { + let [plugin, visitor] = visitors[visit.visitorIndex] + visit.visitorIndex += 1 + if (visit.visitorIndex === visitors.length) { + visit.visitors = [] + visit.visitorIndex = 0 + } + this.result.lastPlugin = plugin + try { + return visitor(node.toProxy(), this.helpers) + } catch (e) { + throw this.handleError(e, node) + } + } + + if (visit.iterator !== 0) { + let iterator = visit.iterator + let child + while ((child = node.nodes[node.indexes[iterator]])) { + node.indexes[iterator] += 1 + if (!child[isClean]) { + child[isClean] = true + stack.push(toStack(child)) + return + } + } + visit.iterator = 0 + delete node.indexes[iterator] + } + + let events = visit.events + while (visit.eventIndex < events.length) { + let event = events[visit.eventIndex] + visit.eventIndex += 1 + if (event === CHILDREN) { + if (node.nodes && node.nodes.length) { + node[isClean] = true + visit.iterator = node.getIterator() + } + return + } else if (this.listeners[event]) { + visit.visitors = this.listeners[event] + return + } + } + stack.pop() + } +} + +LazyResult.registerPostcss = dependant => { + postcss = dependant +} + +module.exports = LazyResult +LazyResult.default = LazyResult + +Root.registerLazyResult(LazyResult) +Document.registerLazyResult(LazyResult) diff --git a/node_modules/postcss/lib/list.d.ts b/node_modules/postcss/lib/list.d.ts new file mode 100644 index 0000000..79841ed --- /dev/null +++ b/node_modules/postcss/lib/list.d.ts @@ -0,0 +1,51 @@ +export type List = { + /** + * Safely splits values. + * + * ```js + * Once (root, { list }) { + * list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)'] + * } + * ``` + * + * @param string separated values. + * @param separators array of separators. + * @param last boolean indicator. + * @return Split values. + */ + split(string: string, separators: string[], last: boolean): string[] + /** + * Safely splits space-separated values (such as those for `background`, + * `border-radius`, and other shorthand properties). + * + * ```js + * Once (root, { list }) { + * list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)'] + * } + * ``` + * + * @param str Space-separated values. + * @return Split values. + */ + space(str: string): string[] + + /** + * Safely splits comma-separated values (such as those for `transition-*` + * and `background` properties). + * + * ```js + * Once (root, { list }) { + * list.comma('black, linear-gradient(white, black)') + * //=> ['black', 'linear-gradient(white, black)'] + * } + * ``` + * + * @param str Comma-separated values. + * @return Split values. + */ + comma(str: string): string[] +} + +declare const list: List + +export default list diff --git a/node_modules/postcss/lib/list.js b/node_modules/postcss/lib/list.js new file mode 100644 index 0000000..c3f9646 --- /dev/null +++ b/node_modules/postcss/lib/list.js @@ -0,0 +1,58 @@ +'use strict' + +let list = { + split(string, separators, last) { + let array = [] + let current = '' + let split = false + + let func = 0 + let inQuote = false + let prevQuote = '' + let escape = false + + for (let letter of string) { + if (escape) { + escape = false + } else if (letter === '\\') { + escape = true + } else if (inQuote) { + if (letter === prevQuote) { + inQuote = false + } + } else if (letter === '"' || letter === "'") { + inQuote = true + prevQuote = letter + } else if (letter === '(') { + func += 1 + } else if (letter === ')') { + if (func > 0) func -= 1 + } else if (func === 0) { + if (separators.includes(letter)) split = true + } + + if (split) { + if (current !== '') array.push(current.trim()) + current = '' + split = false + } else { + current += letter + } + } + + if (last || current !== '') array.push(current.trim()) + return array + }, + + space(string) { + let spaces = [' ', '\n', '\t'] + return list.split(string, spaces) + }, + + comma(string) { + return list.split(string, [','], true) + } +} + +module.exports = list +list.default = list diff --git a/node_modules/postcss/lib/map-generator.js b/node_modules/postcss/lib/map-generator.js new file mode 100644 index 0000000..a1ea65e --- /dev/null +++ b/node_modules/postcss/lib/map-generator.js @@ -0,0 +1,338 @@ +'use strict' + +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { dirname, resolve, relative, sep } = require('path') +let { pathToFileURL } = require('url') + +let Input = require('./input') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(dirname && resolve && relative && sep) + +class MapGenerator { + constructor(stringify, root, opts, cssString) { + this.stringify = stringify + this.mapOpts = opts.map || {} + this.root = root + this.opts = opts + this.css = cssString + this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute + } + + isMap() { + if (typeof this.opts.map !== 'undefined') { + return !!this.opts.map + } + return this.previous().length > 0 + } + + previous() { + if (!this.previousMaps) { + this.previousMaps = [] + if (this.root) { + this.root.walk(node => { + if (node.source && node.source.input.map) { + let map = node.source.input.map + if (!this.previousMaps.includes(map)) { + this.previousMaps.push(map) + } + } + }) + } else { + let input = new Input(this.css, this.opts) + if (input.map) this.previousMaps.push(input.map) + } + } + + return this.previousMaps + } + + isInline() { + if (typeof this.mapOpts.inline !== 'undefined') { + return this.mapOpts.inline + } + + let annotation = this.mapOpts.annotation + if (typeof annotation !== 'undefined' && annotation !== true) { + return false + } + + if (this.previous().length) { + return this.previous().some(i => i.inline) + } + return true + } + + isSourcesContent() { + if (typeof this.mapOpts.sourcesContent !== 'undefined') { + return this.mapOpts.sourcesContent + } + if (this.previous().length) { + return this.previous().some(i => i.withContent()) + } + return true + } + + clearAnnotation() { + if (this.mapOpts.annotation === false) return + + if (this.root) { + let node + for (let i = this.root.nodes.length - 1; i >= 0; i--) { + node = this.root.nodes[i] + if (node.type !== 'comment') continue + if (node.text.indexOf('# sourceMappingURL=') === 0) { + this.root.removeChild(i) + } + } + } else if (this.css) { + this.css = this.css.replace(/(\n)?\/\*#[\S\s]*?\*\/$/gm, '') + } + } + + setSourcesContent() { + let already = {} + if (this.root) { + this.root.walk(node => { + if (node.source) { + let from = node.source.input.from + if (from && !already[from]) { + already[from] = true + let fromUrl = this.usesFileUrls + ? this.toFileUrl(from) + : this.toUrl(this.path(from)) + this.map.setSourceContent(fromUrl, node.source.input.css) + } + } + }) + } else if (this.css) { + let from = this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '' + this.map.setSourceContent(from, this.css) + } + } + + applyPrevMaps() { + for (let prev of this.previous()) { + let from = this.toUrl(this.path(prev.file)) + let root = prev.root || dirname(prev.file) + let map + + if (this.mapOpts.sourcesContent === false) { + map = new SourceMapConsumer(prev.text) + if (map.sourcesContent) { + map.sourcesContent = map.sourcesContent.map(() => null) + } + } else { + map = prev.consumer() + } + + this.map.applySourceMap(map, from, this.toUrl(this.path(root))) + } + } + + isAnnotation() { + if (this.isInline()) { + return true + } + if (typeof this.mapOpts.annotation !== 'undefined') { + return this.mapOpts.annotation + } + if (this.previous().length) { + return this.previous().some(i => i.annotation) + } + return true + } + + toBase64(str) { + if (Buffer) { + return Buffer.from(str).toString('base64') + } else { + return window.btoa(unescape(encodeURIComponent(str))) + } + } + + addAnnotation() { + let content + + if (this.isInline()) { + content = + 'data:application/json;base64,' + this.toBase64(this.map.toString()) + } else if (typeof this.mapOpts.annotation === 'string') { + content = this.mapOpts.annotation + } else if (typeof this.mapOpts.annotation === 'function') { + content = this.mapOpts.annotation(this.opts.to, this.root) + } else { + content = this.outputFile() + '.map' + } + let eol = '\n' + if (this.css.includes('\r\n')) eol = '\r\n' + + this.css += eol + '/*# sourceMappingURL=' + content + ' */' + } + + outputFile() { + if (this.opts.to) { + return this.path(this.opts.to) + } else if (this.opts.from) { + return this.path(this.opts.from) + } else { + return 'to.css' + } + } + + generateMap() { + if (this.root) { + this.generateString() + } else if (this.previous().length === 1) { + let prev = this.previous()[0].consumer() + prev.file = this.outputFile() + this.map = SourceMapGenerator.fromSourceMap(prev) + } else { + this.map = new SourceMapGenerator({ file: this.outputFile() }) + this.map.addMapping({ + source: this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '', + generated: { line: 1, column: 0 }, + original: { line: 1, column: 0 } + }) + } + + if (this.isSourcesContent()) this.setSourcesContent() + if (this.root && this.previous().length > 0) this.applyPrevMaps() + if (this.isAnnotation()) this.addAnnotation() + + if (this.isInline()) { + return [this.css] + } else { + return [this.css, this.map] + } + } + + path(file) { + if (file.indexOf('<') === 0) return file + if (/^\w+:\/\//.test(file)) return file + if (this.mapOpts.absolute) return file + + let from = this.opts.to ? dirname(this.opts.to) : '.' + + if (typeof this.mapOpts.annotation === 'string') { + from = dirname(resolve(from, this.mapOpts.annotation)) + } + + file = relative(from, file) + return file + } + + toUrl(path) { + if (sep === '\\') { + path = path.replace(/\\/g, '/') + } + return encodeURI(path).replace(/[#?]/g, encodeURIComponent) + } + + toFileUrl(path) { + if (pathToFileURL) { + return pathToFileURL(path).toString() + } else { + throw new Error( + '`map.absolute` option is not available in this PostCSS build' + ) + } + } + + sourcePath(node) { + if (this.mapOpts.from) { + return this.toUrl(this.mapOpts.from) + } else if (this.usesFileUrls) { + return this.toFileUrl(node.source.input.from) + } else { + return this.toUrl(this.path(node.source.input.from)) + } + } + + generateString() { + this.css = '' + this.map = new SourceMapGenerator({ file: this.outputFile() }) + + let line = 1 + let column = 1 + + let noSource = '' + let mapping = { + source: '', + generated: { line: 0, column: 0 }, + original: { line: 0, column: 0 } + } + + let lines, last + this.stringify(this.root, (str, node, type) => { + this.css += str + + if (node && type !== 'end') { + mapping.generated.line = line + mapping.generated.column = column - 1 + if (node.source && node.source.start) { + mapping.source = this.sourcePath(node) + mapping.original.line = node.source.start.line + mapping.original.column = node.source.start.column - 1 + this.map.addMapping(mapping) + } else { + mapping.source = noSource + mapping.original.line = 1 + mapping.original.column = 0 + this.map.addMapping(mapping) + } + } + + lines = str.match(/\n/g) + if (lines) { + line += lines.length + last = str.lastIndexOf('\n') + column = str.length - last + } else { + column += str.length + } + + if (node && type !== 'start') { + let p = node.parent || { raws: {} } + let childless = + node.type === 'decl' || (node.type === 'atrule' && !node.nodes) + if (!childless || node !== p.last || p.raws.semicolon) { + if (node.source && node.source.end) { + mapping.source = this.sourcePath(node) + mapping.original.line = node.source.end.line + mapping.original.column = node.source.end.column - 1 + mapping.generated.line = line + mapping.generated.column = column - 2 + this.map.addMapping(mapping) + } else { + mapping.source = noSource + mapping.original.line = 1 + mapping.original.column = 0 + mapping.generated.line = line + mapping.generated.column = column - 1 + this.map.addMapping(mapping) + } + } + } + }) + } + + generate() { + this.clearAnnotation() + if (pathAvailable && sourceMapAvailable && this.isMap()) { + return this.generateMap() + } else { + let result = '' + this.stringify(this.root, i => { + result += i + }) + return [result] + } + } +} + +module.exports = MapGenerator diff --git a/node_modules/postcss/lib/no-work-result.d.ts b/node_modules/postcss/lib/no-work-result.d.ts new file mode 100644 index 0000000..7ba1462 --- /dev/null +++ b/node_modules/postcss/lib/no-work-result.d.ts @@ -0,0 +1,37 @@ +import Result, { Message, ResultOptions } from './result.js' +import { SourceMap } from './postcss.js' +import Processor from './processor.js' +import Warning from './warning.js' +import Root from './root.js' +import LazyResult from './lazy-result.js' + +/** + * A Promise proxy for the result of PostCSS transformations. + * This lazy result instance doesn't parse css unless `NoWorkResult#root` or `Result#root` + * are accessed. See the example below for details. + * A `NoWork` instance is returned by `Processor#process` ONLY when no plugins defined. + * + * ```js + * const noWorkResult = postcss().process(css) // No plugins are defined. + * // CSS is not parsed + * let root = noWorkResult.root // now css is parsed because we accessed the root + * ``` + */ +export default class NoWorkResult implements LazyResult { + then: Promise['then'] + catch: Promise['catch'] + finally: Promise['finally'] + constructor(processor: Processor, css: string, opts: ResultOptions) + get [Symbol.toStringTag](): string + get processor(): Processor + get opts(): ResultOptions + get css(): string + get content(): string + get map(): SourceMap + get root(): Root + get messages(): Message[] + warnings(): Warning[] + toString(): string + sync(): Result + async(): Promise +} diff --git a/node_modules/postcss/lib/no-work-result.js b/node_modules/postcss/lib/no-work-result.js new file mode 100644 index 0000000..8bab6f5 --- /dev/null +++ b/node_modules/postcss/lib/no-work-result.js @@ -0,0 +1,135 @@ +'use strict' + +let MapGenerator = require('./map-generator') +let stringify = require('./stringify') +let warnOnce = require('./warn-once') +let parse = require('./parse') +const Result = require('./result') + +class NoWorkResult { + constructor(processor, css, opts) { + css = css.toString() + this.stringified = false + + this._processor = processor + this._css = css + this._opts = opts + this._map = undefined + let root + + let str = stringify + this.result = new Result(this._processor, root, this._opts) + this.result.css = css + + let self = this + Object.defineProperty(this.result, 'root', { + get() { + return self.root + } + }) + + let map = new MapGenerator(str, root, this._opts, css) + if (map.isMap()) { + let [generatedCSS, generatedMap] = map.generate() + if (generatedCSS) { + this.result.css = generatedCSS + } + if (generatedMap) { + this.result.map = generatedMap + } + } + } + + get [Symbol.toStringTag]() { + return 'NoWorkResult' + } + + get processor() { + return this.result.processor + } + + get opts() { + return this.result.opts + } + + get css() { + return this.result.css + } + + get content() { + return this.result.css + } + + get map() { + return this.result.map + } + + get root() { + if (this._root) { + return this._root + } + + let root + let parser = parse + + try { + root = parser(this._css, this._opts) + } catch (error) { + this.error = error + } + + if (this.error) { + throw this.error + } else { + this._root = root + return root + } + } + + get messages() { + return [] + } + + warnings() { + return [] + } + + toString() { + return this._css + } + + then(onFulfilled, onRejected) { + if (process.env.NODE_ENV !== 'production') { + if (!('from' in this._opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ) + } + } + + return this.async().then(onFulfilled, onRejected) + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + async() { + if (this.error) return Promise.reject(this.error) + return Promise.resolve(this.result) + } + + sync() { + if (this.error) throw this.error + return this.result + } +} + +module.exports = NoWorkResult +NoWorkResult.default = NoWorkResult diff --git a/node_modules/postcss/lib/node.d.ts b/node_modules/postcss/lib/node.d.ts new file mode 100644 index 0000000..a97d43a --- /dev/null +++ b/node_modules/postcss/lib/node.d.ts @@ -0,0 +1,478 @@ +import Declaration, { DeclarationProps } from './declaration.js' +import Comment, { CommentProps } from './comment.js' +import { Stringifier, Syntax } from './postcss.js' +import AtRule, { AtRuleProps } from './at-rule.js' +import Rule, { RuleProps } from './rule.js' +import Warning, { WarningOptions } from './warning.js' +import CssSyntaxError from './css-syntax-error.js' +import Result from './result.js' +import Input from './input.js' +import Root from './root.js' +import Document from './document.js' +import Container from './container.js' + +export type ChildNode = AtRule | Rule | Declaration | Comment + +export type AnyNode = AtRule | Rule | Declaration | Comment | Root | Document + +export type ChildProps = + | AtRuleProps + | RuleProps + | DeclarationProps + | CommentProps + +export interface Position { + /** + * Source offset in file. It starts from 0. + */ + offset: number + + /** + * Source line in file. In contrast to `offset` it starts from 1. + */ + column: number + + /** + * Source column in file. + */ + line: number +} + +export interface Range { + /** + * Start position, inclusive. + */ + start: Position + + /** + * End position, exclusive. + */ + end: Position +} + +export interface Source { + /** + * The file source of the node. + */ + input: Input + /** + * The inclusive starting position of the node’s source. + */ + start?: Position + /** + * The inclusive ending position of the node's source. + */ + end?: Position +} + +export interface NodeProps { + source?: Source +} + +interface NodeErrorOptions { + /** + * Plugin name that created this error. PostCSS will set it automatically. + */ + plugin?: string + /** + * A word inside a node's string, that should be highlighted as source + * of error. + */ + word?: string + /** + * An index inside a node's string that should be highlighted as source + * of error. + */ + index?: number + /** + * An ending index inside a node's string that should be highlighted as + * source of error. + */ + endIndex?: number +} + +/** + * All node classes inherit the following common methods. + * + * You should not extend this classes to create AST for selector or value + * parser. + */ +export default abstract class Node { + /** + * tring representing the node’s type. Possible values are `root`, `atrule`, + * `rule`, `decl`, or `comment`. + * + * ```js + * new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl' + * ``` + */ + type: string + + /** + * The node’s parent node. + * + * ```js + * root.nodes[0].parent === root + * ``` + */ + parent: Document | Container | undefined + + /** + * The input source of the node. + * + * The property is used in source map generation. + * + * If you create a node manually (e.g., with `postcss.decl()`), + * that node will not have a `source` property and will be absent + * from the source map. For this reason, the plugin developer should + * consider cloning nodes to create new ones (in which case the new node’s + * source will reference the original, cloned node) or setting + * the `source` property manually. + * + * ```js + * decl.source.input.from //=> '/home/ai/a.sass' + * decl.source.start //=> { line: 10, column: 2 } + * decl.source.end //=> { line: 10, column: 12 } + * ``` + * + * ```js + * // Bad + * const prefixed = postcss.decl({ + * prop: '-moz-' + decl.prop, + * value: decl.value + * }) + * + * // Good + * const prefixed = decl.clone({ prop: '-moz-' + decl.prop }) + * ``` + * + * ```js + * if (atrule.name === 'add-link') { + * const rule = postcss.rule({ selector: 'a', source: atrule.source }) + * atrule.parent.insertBefore(atrule, rule) + * } + * ``` + */ + source?: Source + + /** + * Information to generate byte-to-byte equal node string as it was + * in the origin input. + * + * Every parser saves its own properties, + * but the default CSS parser uses: + * + * * `before`: the space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + * * `after`: the space symbols after the last child of the node + * to the end of the node. + * * `between`: the symbols between the property and value + * for declarations, selector and `{` for rules, or last parameter + * and `{` for at-rules. + * * `semicolon`: contains true if the last child has + * an (optional) semicolon. + * * `afterName`: the space between the at-rule name and its parameters. + * * `left`: the space symbols between `/*` and the comment’s text. + * * `right`: the space symbols between the comment’s text + * and */. + * * `important`: the content of the important statement, + * if it is not just `!important`. + * + * PostCSS cleans selectors, declaration values and at-rule parameters + * from comments and extra spaces, but it stores origin content in raws + * properties. As such, if you don’t change a declaration’s value, + * PostCSS will use the raw value with comments. + * + * ```js + * const root = postcss.parse('a {\n color:black\n}') + * root.first.first.raws //=> { before: '\n ', between: ':' } + * ``` + */ + raws: any + + /** + * @param defaults Value for node properties. + */ + constructor(defaults?: object) + + /** + * Returns a `CssSyntaxError` instance containing the original position + * of the node in the source, showing line and column numbers and also + * a small excerpt to facilitate debugging. + * + * If present, an input source map will be used to get the original position + * of the source, even from a previous compilation step + * (e.g., from Sass compilation). + * + * This method produces very useful error messages. + * + * ```js + * if (!variables[name]) { + * throw decl.error(`Unknown variable ${name}`, { word: name }) + * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + * // color: $black + * // a + * // ^ + * // background: white + * } + * ``` + * + * @param message Error description. + * @param opts Options. + * + * @return Error object to throw it. + */ + error(message: string, options?: NodeErrorOptions): CssSyntaxError + + /** + * This method is provided as a convenience wrapper for `Result#warn`. + * + * ```js + * Declaration: { + * bad: (decl, { result }) => { + * decl.warn(result, 'Deprecated property bad') + * } + * } + * ``` + * + * @param result The `Result` instance that will receive the warning. + * @param text Warning message. + * @param opts Warning Options. + * + * @return Created warning object. + */ + warn(result: Result, text: string, opts?: WarningOptions): Warning + + /** + * Removes the node from its parent and cleans the parent properties + * from the node and its children. + * + * ```js + * if (decl.prop.match(/^-webkit-/)) { + * decl.remove() + * } + * ``` + * + * @return Node to make calls chain. + */ + remove(): this + + /** + * Returns a CSS string representing the node. + * + * ```js + * new Rule({ selector: 'a' }).toString() //=> "a {}" + * ``` + * + * @param stringifier A syntax to use in string generation. + * @return CSS string of this node. + */ + toString(stringifier?: Stringifier | Syntax): string + + /** + * Assigns properties to the current node. + * + * ```js + * decl.assign({ prop: 'word-wrap', value: 'break-word' }) + * ``` + * + * @param overrides New properties to override the node. + * @return Current node to methods chain. + */ + assign(overrides: object): this + + /** + * Returns an exact clone of the node. + * + * The resulting cloned node and its (cloned) children will retain + * code style properties. + * + * ```js + * decl.raws.before //=> "\n " + * const cloned = decl.clone({ prop: '-moz-' + decl.prop }) + * cloned.raws.before //=> "\n " + * cloned.toString() //=> -moz-transform: scale(0) + * ``` + * + * @param overrides New properties to override in the clone. + * @return Clone of the node. + */ + clone(overrides?: object): this + + /** + * Shortcut to clone the node and insert the resulting cloned node + * before the current node. + * + * ```js + * decl.cloneBefore({ prop: '-moz-' + decl.prop }) + * ``` + * + * @param overrides Mew properties to override in the clone. + * + * @return New node + */ + cloneBefore(overrides?: object): this + + /** + * Shortcut to clone the node and insert the resulting cloned node + * after the current node. + * + * @param overrides New properties to override in the clone. + * @return New node. + */ + cloneAfter(overrides?: object): this + + /** + * Inserts node(s) before the current node and removes the current node. + * + * ```js + * AtRule: { + * mixin: atrule => { + * atrule.replaceWith(mixinRules[atrule.params]) + * } + * } + * ``` + * + * @param nodes Mode(s) to replace current one. + * @return Current node to methods chain. + */ + replaceWith( + ...nodes: (ChildNode | ChildProps | ChildNode[] | ChildProps[])[] + ): this + + /** + * Returns the next child of the node’s parent. + * Returns `undefined` if the current node is the last child. + * + * ```js + * if (comment.text === 'delete next') { + * const next = comment.next() + * if (next) { + * next.remove() + * } + * } + * ``` + * + * @return Next node. + */ + next(): ChildNode | undefined + + /** + * Returns the previous child of the node’s parent. + * Returns `undefined` if the current node is the first child. + * + * ```js + * const annotation = decl.prev() + * if (annotation.type === 'comment') { + * readAnnotation(annotation.text) + * } + * ``` + * + * @return Previous node. + */ + prev(): ChildNode | undefined + + /** + * Insert new node before current node to current node’s parent. + * + * Just alias for `node.parent.insertBefore(node, add)`. + * + * ```js + * decl.before('content: ""') + * ``` + * + * @param newNode New node. + * @return This node for methods chain. + */ + before(newNode: Node | ChildProps | string | Node[]): this + + /** + * Insert new node after current node to current node’s parent. + * + * Just alias for `node.parent.insertAfter(node, add)`. + * + * ```js + * decl.after('color: black') + * ``` + * + * @param newNode New node. + * @return This node for methods chain. + */ + after(newNode: Node | ChildProps | string | Node[]): this + + /** + * Finds the Root instance of the node’s tree. + * + * ```js + * root.nodes[0].nodes[0].root() === root + * ``` + * + * @return Root parent. + */ + root(): Root + + /** + * Returns a `Node#raws` value. If the node is missing + * the code style property (because the node was manually built or cloned), + * PostCSS will try to autodetect the code style property by looking + * at other nodes in the tree. + * + * ```js + * const root = postcss.parse('a { background: white }') + * root.nodes[0].append({ prop: 'color', value: 'black' }) + * root.nodes[0].nodes[1].raws.before //=> undefined + * root.nodes[0].nodes[1].raw('before') //=> ' ' + * ``` + * + * @param prop Name of code style property. + * @param defaultType Name of default value, it can be missed + * if the value is the same as prop. + * @return {string} Code style value. + */ + raw(prop: string, defaultType?: string): string + + /** + * Clear the code style properties for the node and its children. + * + * ```js + * node.raws.before //=> ' ' + * node.cleanRaws() + * node.raws.before //=> undefined + * ``` + * + * @param keepBetween Keep the `raws.between` symbols. + */ + cleanRaws(keepBetween?: boolean): void + + /** + * Fix circular links on `JSON.stringify()`. + * + * @return Cleaned object. + */ + toJSON(): object + + /** + * Convert string index to line/column. + * + * @param index The symbol number in the node’s string. + * @return Symbol position in file. + */ + positionInside(index: number): Position + + /** + * Get the position for a word or an index inside the node. + * + * @param opts Options. + * @return Position. + */ + positionBy(opts?: Pick): Position + + /** + * Get the range for a word or start and end index inside the node. + * The start index is inclusive; the end index is exclusive. + * + * @param opts Options. + * @return Range. + */ + rangeBy(opts?: Pick): Range +} diff --git a/node_modules/postcss/lib/node.js b/node_modules/postcss/lib/node.js new file mode 100644 index 0000000..bdcbac0 --- /dev/null +++ b/node_modules/postcss/lib/node.js @@ -0,0 +1,379 @@ +'use strict' + +let { isClean, my } = require('./symbols') +let CssSyntaxError = require('./css-syntax-error') +let Stringifier = require('./stringifier') +let stringify = require('./stringify') + +function cloneNode(obj, parent) { + let cloned = new obj.constructor() + + for (let i in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, i)) { + /* c8 ignore next 2 */ + continue + } + if (i === 'proxyCache') continue + let value = obj[i] + let type = typeof value + + if (i === 'parent' && type === 'object') { + if (parent) cloned[i] = parent + } else if (i === 'source') { + cloned[i] = value + } else if (Array.isArray(value)) { + cloned[i] = value.map(j => cloneNode(j, cloned)) + } else { + if (type === 'object' && value !== null) value = cloneNode(value) + cloned[i] = value + } + } + + return cloned +} + +class Node { + constructor(defaults = {}) { + this.raws = {} + this[isClean] = false + this[my] = true + + for (let name in defaults) { + if (name === 'nodes') { + this.nodes = [] + for (let node of defaults[name]) { + if (typeof node.clone === 'function') { + this.append(node.clone()) + } else { + this.append(node) + } + } + } else { + this[name] = defaults[name] + } + } + } + + error(message, opts = {}) { + if (this.source) { + let { start, end } = this.rangeBy(opts) + return this.source.input.error( + message, + { line: start.line, column: start.column }, + { line: end.line, column: end.column }, + opts + ) + } + return new CssSyntaxError(message) + } + + warn(result, text, opts) { + let data = { node: this } + for (let i in opts) data[i] = opts[i] + return result.warn(text, data) + } + + remove() { + if (this.parent) { + this.parent.removeChild(this) + } + this.parent = undefined + return this + } + + toString(stringifier = stringify) { + if (stringifier.stringify) stringifier = stringifier.stringify + let result = '' + stringifier(this, i => { + result += i + }) + return result + } + + assign(overrides = {}) { + for (let name in overrides) { + this[name] = overrides[name] + } + return this + } + + clone(overrides = {}) { + let cloned = cloneNode(this) + for (let name in overrides) { + cloned[name] = overrides[name] + } + return cloned + } + + cloneBefore(overrides = {}) { + let cloned = this.clone(overrides) + this.parent.insertBefore(this, cloned) + return cloned + } + + cloneAfter(overrides = {}) { + let cloned = this.clone(overrides) + this.parent.insertAfter(this, cloned) + return cloned + } + + replaceWith(...nodes) { + if (this.parent) { + let bookmark = this + let foundSelf = false + for (let node of nodes) { + if (node === this) { + foundSelf = true + } else if (foundSelf) { + this.parent.insertAfter(bookmark, node) + bookmark = node + } else { + this.parent.insertBefore(bookmark, node) + } + } + + if (!foundSelf) { + this.remove() + } + } + + return this + } + + next() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index + 1] + } + + prev() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index - 1] + } + + before(add) { + this.parent.insertBefore(this, add) + return this + } + + after(add) { + this.parent.insertAfter(this, add) + return this + } + + root() { + let result = this + while (result.parent && result.parent.type !== 'document') { + result = result.parent + } + return result + } + + raw(prop, defaultType) { + let str = new Stringifier() + return str.raw(this, prop, defaultType) + } + + cleanRaws(keepBetween) { + delete this.raws.before + delete this.raws.after + if (!keepBetween) delete this.raws.between + } + + toJSON(_, inputs) { + let fixed = {} + let emitInputs = inputs == null + inputs = inputs || new Map() + let inputsNextIndex = 0 + + for (let name in this) { + if (!Object.prototype.hasOwnProperty.call(this, name)) { + /* c8 ignore next 2 */ + continue + } + if (name === 'parent' || name === 'proxyCache') continue + let value = this[name] + + if (Array.isArray(value)) { + fixed[name] = value.map(i => { + if (typeof i === 'object' && i.toJSON) { + return i.toJSON(null, inputs) + } else { + return i + } + }) + } else if (typeof value === 'object' && value.toJSON) { + fixed[name] = value.toJSON(null, inputs) + } else if (name === 'source') { + let inputId = inputs.get(value.input) + if (inputId == null) { + inputId = inputsNextIndex + inputs.set(value.input, inputsNextIndex) + inputsNextIndex++ + } + fixed[name] = { + inputId, + start: value.start, + end: value.end + } + } else { + fixed[name] = value + } + } + + if (emitInputs) { + fixed.inputs = [...inputs.keys()].map(input => input.toJSON()) + } + + return fixed + } + + positionInside(index) { + let string = this.toString() + let column = this.source.start.column + let line = this.source.start.line + + for (let i = 0; i < index; i++) { + if (string[i] === '\n') { + column = 1 + line += 1 + } else { + column += 1 + } + } + + return { line, column } + } + + positionBy(opts) { + let pos = this.source.start + if (opts.index) { + pos = this.positionInside(opts.index) + } else if (opts.word) { + let index = this.toString().indexOf(opts.word) + if (index !== -1) pos = this.positionInside(index) + } + return pos + } + + rangeBy(opts) { + let start = { + line: this.source.start.line, + column: this.source.start.column + } + let end = this.source.end + ? { + line: this.source.end.line, + column: this.source.end.column + 1 + } + : { + line: start.line, + column: start.column + 1 + } + + if (opts.word) { + let index = this.toString().indexOf(opts.word) + if (index !== -1) { + start = this.positionInside(index) + end = this.positionInside(index + opts.word.length) + } + } else { + if (opts.start) { + start = { + line: opts.start.line, + column: opts.start.column + } + } else if (opts.index) { + start = this.positionInside(opts.index) + } + + if (opts.end) { + end = { + line: opts.end.line, + column: opts.end.column + } + } else if (opts.endIndex) { + end = this.positionInside(opts.endIndex) + } else if (opts.index) { + end = this.positionInside(opts.index + 1) + } + } + + if ( + end.line < start.line || + (end.line === start.line && end.column <= start.column) + ) { + end = { line: start.line, column: start.column + 1 } + } + + return { start, end } + } + + getProxyProcessor() { + return { + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value + if ( + prop === 'prop' || + prop === 'value' || + prop === 'name' || + prop === 'params' || + prop === 'important' || + /* c8 ignore next */ + prop === 'text' + ) { + node.markDirty() + } + return true + }, + + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (prop === 'root') { + return () => node.root().toProxy() + } else { + return node[prop] + } + } + } + } + + toProxy() { + if (!this.proxyCache) { + this.proxyCache = new Proxy(this, this.getProxyProcessor()) + } + return this.proxyCache + } + + addToError(error) { + error.postcssNode = this + if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { + let s = this.source + error.stack = error.stack.replace( + /\n\s{4}at /, + `$&${s.input.from}:${s.start.line}:${s.start.column}$&` + ) + } + return error + } + + markDirty() { + if (this[isClean]) { + this[isClean] = false + let next = this + while ((next = next.parent)) { + next[isClean] = false + } + } + } + + get proxyOf() { + return this + } +} + +module.exports = Node +Node.default = Node diff --git a/node_modules/postcss/lib/parse.d.ts b/node_modules/postcss/lib/parse.d.ts new file mode 100644 index 0000000..d6bdee2 --- /dev/null +++ b/node_modules/postcss/lib/parse.d.ts @@ -0,0 +1,5 @@ +import { Parser } from './postcss.js' + +declare const parse: Parser + +export default parse diff --git a/node_modules/postcss/lib/parse.js b/node_modules/postcss/lib/parse.js new file mode 100644 index 0000000..971431f --- /dev/null +++ b/node_modules/postcss/lib/parse.js @@ -0,0 +1,42 @@ +'use strict' + +let Container = require('./container') +let Parser = require('./parser') +let Input = require('./input') + +function parse(css, opts) { + let input = new Input(css, opts) + let parser = new Parser(input) + try { + parser.parse() + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + if (e.name === 'CssSyntaxError' && opts && opts.from) { + if (/\.scss$/i.test(opts.from)) { + e.message += + '\nYou tried to parse SCSS with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-scss parser' + } else if (/\.sass/i.test(opts.from)) { + e.message += + '\nYou tried to parse Sass with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-sass parser' + } else if (/\.less$/i.test(opts.from)) { + e.message += + '\nYou tried to parse Less with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-less parser' + } + } + } + throw e + } + + return parser.root +} + +module.exports = parse +parse.default = parse + +Container.registerParse(parse) diff --git a/node_modules/postcss/lib/parser.js b/node_modules/postcss/lib/parser.js new file mode 100644 index 0000000..752d264 --- /dev/null +++ b/node_modules/postcss/lib/parser.js @@ -0,0 +1,603 @@ +'use strict' + +let Declaration = require('./declaration') +let tokenizer = require('./tokenize') +let Comment = require('./comment') +let AtRule = require('./at-rule') +let Root = require('./root') +let Rule = require('./rule') + +const SAFE_COMMENT_NEIGHBOR = { + empty: true, + space: true +} + +function findLastWithPosition(tokens) { + for (let i = tokens.length - 1; i >= 0; i--) { + let token = tokens[i] + let pos = token[3] || token[2] + if (pos) return pos + } +} + +class Parser { + constructor(input) { + this.input = input + + this.root = new Root() + this.current = this.root + this.spaces = '' + this.semicolon = false + this.customProperty = false + + this.createTokenizer() + this.root.source = { input, start: { offset: 0, line: 1, column: 1 } } + } + + createTokenizer() { + this.tokenizer = tokenizer(this.input) + } + + parse() { + let token + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + + switch (token[0]) { + case 'space': + this.spaces += token[1] + break + + case ';': + this.freeSemicolon(token) + break + + case '}': + this.end(token) + break + + case 'comment': + this.comment(token) + break + + case 'at-word': + this.atrule(token) + break + + case '{': + this.emptyRule(token) + break + + default: + this.other(token) + break + } + } + this.endFile() + } + + comment(token) { + let node = new Comment() + this.init(node, token[2]) + node.source.end = this.getPosition(token[3] || token[2]) + + let text = token[1].slice(2, -2) + if (/^\s*$/.test(text)) { + node.text = '' + node.raws.left = text + node.raws.right = '' + } else { + let match = text.match(/^(\s*)([^]*\S)(\s*)$/) + node.text = match[2] + node.raws.left = match[1] + node.raws.right = match[3] + } + } + + emptyRule(token) { + let node = new Rule() + this.init(node, token[2]) + node.selector = '' + node.raws.between = '' + this.current = node + } + + other(start) { + let end = false + let type = null + let colon = false + let bracket = null + let brackets = [] + let customProperty = start[1].startsWith('--') + + let tokens = [] + let token = start + while (token) { + type = token[0] + tokens.push(token) + + if (type === '(' || type === '[') { + if (!bracket) bracket = token + brackets.push(type === '(' ? ')' : ']') + } else if (customProperty && colon && type === '{') { + if (!bracket) bracket = token + brackets.push('}') + } else if (brackets.length === 0) { + if (type === ';') { + if (colon) { + this.decl(tokens, customProperty) + return + } else { + break + } + } else if (type === '{') { + this.rule(tokens) + return + } else if (type === '}') { + this.tokenizer.back(tokens.pop()) + end = true + break + } else if (type === ':') { + colon = true + } + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + if (brackets.length === 0) bracket = null + } + + token = this.tokenizer.nextToken() + } + + if (this.tokenizer.endOfFile()) end = true + if (brackets.length > 0) this.unclosedBracket(bracket) + + if (end && colon) { + if (!customProperty) { + while (tokens.length) { + token = tokens[tokens.length - 1][0] + if (token !== 'space' && token !== 'comment') break + this.tokenizer.back(tokens.pop()) + } + } + this.decl(tokens, customProperty) + } else { + this.unknownWord(tokens) + } + } + + rule(tokens) { + tokens.pop() + + let node = new Rule() + this.init(node, tokens[0][2]) + + node.raws.between = this.spacesAndCommentsFromEnd(tokens) + this.raw(node, 'selector', tokens) + this.current = node + } + + decl(tokens, customProperty) { + let node = new Declaration() + this.init(node, tokens[0][2]) + + let last = tokens[tokens.length - 1] + if (last[0] === ';') { + this.semicolon = true + tokens.pop() + } + + node.source.end = this.getPosition( + last[3] || last[2] || findLastWithPosition(tokens) + ) + + while (tokens[0][0] !== 'word') { + if (tokens.length === 1) this.unknownWord(tokens) + node.raws.before += tokens.shift()[1] + } + node.source.start = this.getPosition(tokens[0][2]) + + node.prop = '' + while (tokens.length) { + let type = tokens[0][0] + if (type === ':' || type === 'space' || type === 'comment') { + break + } + node.prop += tokens.shift()[1] + } + + node.raws.between = '' + + let token + while (tokens.length) { + token = tokens.shift() + + if (token[0] === ':') { + node.raws.between += token[1] + break + } else { + if (token[0] === 'word' && /\w/.test(token[1])) { + this.unknownWord([token]) + } + node.raws.between += token[1] + } + } + + if (node.prop[0] === '_' || node.prop[0] === '*') { + node.raws.before += node.prop[0] + node.prop = node.prop.slice(1) + } + + let firstSpaces = [] + let next + while (tokens.length) { + next = tokens[0][0] + if (next !== 'space' && next !== 'comment') break + firstSpaces.push(tokens.shift()) + } + + this.precheckMissedSemicolon(tokens) + + for (let i = tokens.length - 1; i >= 0; i--) { + token = tokens[i] + if (token[1].toLowerCase() === '!important') { + node.important = true + let string = this.stringFrom(tokens, i) + string = this.spacesFromEnd(tokens) + string + if (string !== ' !important') node.raws.important = string + break + } else if (token[1].toLowerCase() === 'important') { + let cache = tokens.slice(0) + let str = '' + for (let j = i; j > 0; j--) { + let type = cache[j][0] + if (str.trim().indexOf('!') === 0 && type !== 'space') { + break + } + str = cache.pop()[1] + str + } + if (str.trim().indexOf('!') === 0) { + node.important = true + node.raws.important = str + tokens = cache + } + } + + if (token[0] !== 'space' && token[0] !== 'comment') { + break + } + } + + let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment') + + if (hasWord) { + node.raws.between += firstSpaces.map(i => i[1]).join('') + firstSpaces = [] + } + this.raw(node, 'value', firstSpaces.concat(tokens), customProperty) + + if (node.value.includes(':') && !customProperty) { + this.checkMissedSemicolon(tokens) + } + } + + atrule(token) { + let node = new AtRule() + node.name = token[1].slice(1) + if (node.name === '') { + this.unnamedAtrule(node, token) + } + this.init(node, token[2]) + + let type + let prev + let shift + let last = false + let open = false + let params = [] + let brackets = [] + + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + type = token[0] + + if (type === '(' || type === '[') { + brackets.push(type === '(' ? ')' : ']') + } else if (type === '{' && brackets.length > 0) { + brackets.push('}') + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + } + + if (brackets.length === 0) { + if (type === ';') { + node.source.end = this.getPosition(token[2]) + this.semicolon = true + break + } else if (type === '{') { + open = true + break + } else if (type === '}') { + if (params.length > 0) { + shift = params.length - 1 + prev = params[shift] + while (prev && prev[0] === 'space') { + prev = params[--shift] + } + if (prev) { + node.source.end = this.getPosition(prev[3] || prev[2]) + } + } + this.end(token) + break + } else { + params.push(token) + } + } else { + params.push(token) + } + + if (this.tokenizer.endOfFile()) { + last = true + break + } + } + + node.raws.between = this.spacesAndCommentsFromEnd(params) + if (params.length) { + node.raws.afterName = this.spacesAndCommentsFromStart(params) + this.raw(node, 'params', params) + if (last) { + token = params[params.length - 1] + node.source.end = this.getPosition(token[3] || token[2]) + this.spaces = node.raws.between + node.raws.between = '' + } + } else { + node.raws.afterName = '' + node.params = '' + } + + if (open) { + node.nodes = [] + this.current = node + } + } + + end(token) { + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon + } + this.semicolon = false + + this.current.raws.after = (this.current.raws.after || '') + this.spaces + this.spaces = '' + + if (this.current.parent) { + this.current.source.end = this.getPosition(token[2]) + this.current = this.current.parent + } else { + this.unexpectedClose(token) + } + } + + endFile() { + if (this.current.parent) this.unclosedBlock() + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon + } + this.current.raws.after = (this.current.raws.after || '') + this.spaces + } + + freeSemicolon(token) { + this.spaces += token[1] + if (this.current.nodes) { + let prev = this.current.nodes[this.current.nodes.length - 1] + if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) { + prev.raws.ownSemicolon = this.spaces + this.spaces = '' + } + } + } + + // Helpers + + getPosition(offset) { + let pos = this.input.fromOffset(offset) + return { + offset, + line: pos.line, + column: pos.col + } + } + + init(node, offset) { + this.current.push(node) + node.source = { + start: this.getPosition(offset), + input: this.input + } + node.raws.before = this.spaces + this.spaces = '' + if (node.type !== 'comment') this.semicolon = false + } + + raw(node, prop, tokens, customProperty) { + let token, type + let length = tokens.length + let value = '' + let clean = true + let next, prev + + for (let i = 0; i < length; i += 1) { + token = tokens[i] + type = token[0] + if (type === 'space' && i === length - 1 && !customProperty) { + clean = false + } else if (type === 'comment') { + prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty' + next = tokens[i + 1] ? tokens[i + 1][0] : 'empty' + if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) { + if (value.slice(-1) === ',') { + clean = false + } else { + value += token[1] + } + } else { + clean = false + } + } else { + value += token[1] + } + } + if (!clean) { + let raw = tokens.reduce((all, i) => all + i[1], '') + node.raws[prop] = { value, raw } + } + node[prop] = value + } + + spacesAndCommentsFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space' && lastTokenType !== 'comment') break + spaces = tokens.pop()[1] + spaces + } + return spaces + } + + spacesAndCommentsFromStart(tokens) { + let next + let spaces = '' + while (tokens.length) { + next = tokens[0][0] + if (next !== 'space' && next !== 'comment') break + spaces += tokens.shift()[1] + } + return spaces + } + + spacesFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space') break + spaces = tokens.pop()[1] + spaces + } + return spaces + } + + stringFrom(tokens, from) { + let result = '' + for (let i = from; i < tokens.length; i++) { + result += tokens[i][1] + } + tokens.splice(from, tokens.length - from) + return result + } + + colon(tokens) { + let brackets = 0 + let token, type, prev + for (let [i, element] of tokens.entries()) { + token = element + type = token[0] + + if (type === '(') { + brackets += 1 + } + if (type === ')') { + brackets -= 1 + } + if (brackets === 0 && type === ':') { + if (!prev) { + this.doubleColon(token) + } else if (prev[0] === 'word' && prev[1] === 'progid') { + continue + } else { + return i + } + } + + prev = token + } + return false + } + + // Errors + + unclosedBracket(bracket) { + throw this.input.error( + 'Unclosed bracket', + { offset: bracket[2] }, + { offset: bracket[2] + 1 } + ) + } + + unknownWord(tokens) { + throw this.input.error( + 'Unknown word', + { offset: tokens[0][2] }, + { offset: tokens[0][2] + tokens[0][1].length } + ) + } + + unexpectedClose(token) { + throw this.input.error( + 'Unexpected }', + { offset: token[2] }, + { offset: token[2] + 1 } + ) + } + + unclosedBlock() { + let pos = this.current.source.start + throw this.input.error('Unclosed block', pos.line, pos.column) + } + + doubleColon(token) { + throw this.input.error( + 'Double colon', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } + + unnamedAtrule(node, token) { + throw this.input.error( + 'At-rule without name', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } + + precheckMissedSemicolon(/* tokens */) { + // Hook for Safe Parser + } + + checkMissedSemicolon(tokens) { + let colon = this.colon(tokens) + if (colon === false) return + + let founded = 0 + let token + for (let j = colon - 1; j >= 0; j--) { + token = tokens[j] + if (token[0] !== 'space') { + founded += 1 + if (founded === 2) break + } + } + // If the token is a word, e.g. `!important`, `red` or any other valid property's value. + // Then we need to return the colon after that word token. [3] is the "end" colon of that word. + // And because we need it after that one we do +1 to get the next one. + throw this.input.error( + 'Missed semicolon', + token[0] === 'word' ? token[3] + 1 : token[2] + ) + } +} + +module.exports = Parser diff --git a/node_modules/postcss/lib/postcss.d.ts b/node_modules/postcss/lib/postcss.d.ts new file mode 100644 index 0000000..30a0d08 --- /dev/null +++ b/node_modules/postcss/lib/postcss.d.ts @@ -0,0 +1,473 @@ +import { SourceMapGenerator, RawSourceMap } from 'source-map-js' + +import Node, { + Position, + Source, + ChildNode, + NodeErrorOptions, + NodeProps, + ChildProps, + AnyNode +} from './node.js' +import Declaration, { DeclarationProps } from './declaration.js' +import Container, { ContainerProps } from './container.js' +import Document, { DocumentProps } from './document.js' +import Warning, { WarningOptions } from './warning.js' +import Comment, { CommentProps } from './comment.js' +import AtRule, { AtRuleProps } from './at-rule.js' +import Input, { FilePosition } from './input.js' +import Result, { Message } from './result.js' +import Root, { RootProps } from './root.js' +import Rule, { RuleProps } from './rule.js' +import CssSyntaxError from './css-syntax-error.js' +import list, { List } from './list.js' +import LazyResult from './lazy-result.js' +import Processor from './processor.js' + +export { + NodeErrorOptions, + DeclarationProps, + CssSyntaxError, + ContainerProps, + WarningOptions, + DocumentProps, + FilePosition, + CommentProps, + AtRuleProps, + Declaration, + ChildProps, + LazyResult, + ChildNode, + NodeProps, + Processor, + RuleProps, + RootProps, + Container, + Position, + Document, + AnyNode, + Warning, + Message, + Comment, + Source, + AtRule, + Result, + Input, + Node, + list, + Rule, + Root +} + +export type SourceMap = SourceMapGenerator & { + toJSON(): RawSourceMap +} + +export type Helpers = { result: Result; postcss: Postcss } & Postcss + +type DocumentProcessor = ( + document: Document, + helper: Helpers +) => Promise | void +type RootProcessor = (root: Root, helper: Helpers) => Promise | void +type DeclarationProcessor = ( + decl: Declaration, + helper: Helpers +) => Promise | void +type RuleProcessor = (rule: Rule, helper: Helpers) => Promise | void +type AtRuleProcessor = (atRule: AtRule, helper: Helpers) => Promise | void +type CommentProcessor = ( + comment: Comment, + helper: Helpers +) => Promise | void + +interface Processors { + /** + * Will be called on `Document` node. + * + * Will be called again on children changes. + */ + Document?: DocumentProcessor + + /** + * Will be called on `Document` node, when all children will be processed. + * + * Will be called again on children changes. + */ + DocumentExit?: DocumentProcessor + + /** + * Will be called on `Root` node once. + */ + Once?: RootProcessor + + /** + * Will be called on `Root` node once, when all children will be processed. + */ + OnceExit?: RootProcessor + + /** + * Will be called on `Root` node. + * + * Will be called again on children changes. + */ + Root?: RootProcessor + + /** + * Will be called on `Root` node, when all children will be processed. + * + * Will be called again on children changes. + */ + RootExit?: RootProcessor + + /** + * Will be called on all `Declaration` nodes after listeners + * for `Declaration` event. + * + * Will be called again on node or children changes. + */ + Declaration?: DeclarationProcessor | { [prop: string]: DeclarationProcessor } + + /** + * Will be called on all `Declaration` nodes. + * + * Will be called again on node or children changes. + */ + DeclarationExit?: + | DeclarationProcessor + | { [prop: string]: DeclarationProcessor } + + /** + * Will be called on all `Rule` nodes. + * + * Will be called again on node or children changes. + */ + Rule?: RuleProcessor + + /** + * Will be called on all `Rule` nodes, when all children will be processed. + * + * Will be called again on node or children changes. + */ + RuleExit?: RuleProcessor + + /** + * Will be called on all`AtRule` nodes. + * + * Will be called again on node or children changes. + */ + AtRule?: AtRuleProcessor | { [name: string]: AtRuleProcessor } + + /** + * Will be called on all `AtRule` nodes, when all children will be processed. + * + * Will be called again on node or children changes. + */ + AtRuleExit?: AtRuleProcessor | { [name: string]: AtRuleProcessor } + + /** + * Will be called on all `Comment` nodes. + * + * Will be called again on node or children changes. + */ + Comment?: CommentProcessor + + /** + * Will be called on all `Comment` nodes after listeners + * for `Comment` event. + * + * Will be called again on node or children changes. + */ + CommentExit?: CommentProcessor + + /** + * Will be called when all other listeners processed the document. + * + * This listener will not be called again. + */ + Exit?: RootProcessor +} + +export interface Plugin extends Processors { + postcssPlugin: string + prepare?: (result: Result) => Processors +} + +export interface PluginCreator { + (opts?: PluginOptions): Plugin | Processor + postcss: true +} + +export interface Transformer extends TransformCallback { + postcssPlugin: string + postcssVersion: string +} + +export interface TransformCallback { + (root: Root, result: Result): Promise | void +} + +export interface OldPlugin extends Transformer { + (opts?: T): Transformer + postcss: Transformer +} + +export type AcceptedPlugin = + | Plugin + | PluginCreator + | OldPlugin + | TransformCallback + | { + postcss: TransformCallback | Processor + } + | Processor + +export interface Parser { + ( + css: string | { toString(): string }, + opts?: Pick + ): RootNode +} + +export interface Builder { + (part: string, node?: AnyNode, type?: 'start' | 'end'): void +} + +export interface Stringifier { + (node: AnyNode, builder: Builder): void +} + +export interface JSONHydrator { + (data: object[]): Node[] + (data: object): Node +} + +export interface Syntax { + /** + * Function to generate AST by string. + */ + parse?: Parser + + /** + * Class to generate string by AST. + */ + stringify?: Stringifier +} + +export interface SourceMapOptions { + /** + * Indicates that the source map should be embedded in the output CSS + * as a Base64-encoded comment. By default, it is `true`. + * But if all previous maps are external, not inline, PostCSS will not embed + * the map even if you do not set this option. + * + * If you have an inline source map, the result.map property will be empty, + * as the source map will be contained within the text of `result.css`. + */ + inline?: boolean + + /** + * Source map content from a previous processing step (e.g., Sass). + * + * PostCSS will try to read the previous source map + * automatically (based on comments within the source CSS), but you can use + * this option to identify it manually. + * + * If desired, you can omit the previous map with prev: `false`. + */ + prev?: string | boolean | object | ((file: string) => string) + + /** + * Indicates that PostCSS should set the origin content (e.g., Sass source) + * of the source map. By default, it is true. But if all previous maps do not + * contain sources content, PostCSS will also leave it out even if you + * do not set this option. + */ + sourcesContent?: boolean + + /** + * Indicates that PostCSS should add annotation comments to the CSS. + * By default, PostCSS will always add a comment with a path + * to the source map. PostCSS will not add annotations to CSS files + * that do not contain any comments. + * + * By default, PostCSS presumes that you want to save the source map as + * `opts.to + '.map'` and will use this path in the annotation comment. + * A different path can be set by providing a string value for annotation. + * + * If you have set `inline: true`, annotation cannot be disabled. + */ + annotation?: string | boolean | ((file: string, root: Root) => string) + + /** + * Override `from` in map’s sources. + */ + from?: string + + /** + * Use absolute path in generated source map. + */ + absolute?: boolean +} + +export interface ProcessOptions { + /** + * The path of the CSS source file. You should always set `from`, + * because it is used in source map generation and syntax error messages. + */ + from?: string + + /** + * The path where you'll put the output CSS file. You should always set `to` + * to generate correct source maps. + */ + to?: string + + /** + * Function to generate AST by string. + */ + parser?: Syntax | Parser + + /** + * Class to generate string by AST. + */ + stringifier?: Syntax | Stringifier + + /** + * Object with parse and stringify. + */ + syntax?: Syntax + + /** + * Source map options + */ + map?: SourceMapOptions | boolean +} + +export interface Postcss { + /** + * Create a new `Processor` instance that will apply `plugins` + * as CSS processors. + * + * ```js + * let postcss = require('postcss') + * + * postcss(plugins).process(css, { from, to }).then(result => { + * console.log(result.css) + * }) + * ``` + * + * @param plugins PostCSS plugins. + * @return Processor to process multiple CSS. + */ + (plugins?: AcceptedPlugin[]): Processor + (...plugins: AcceptedPlugin[]): Processor + + /** + * Default function to convert a node tree into a CSS string. + */ + stringify: Stringifier + + /** + * Parses source css and returns a new `Root` or `Document` node, + * which contains the source CSS nodes. + * + * ```js + * // Simple CSS concatenation with source map support + * const root1 = postcss.parse(css1, { from: file1 }) + * const root2 = postcss.parse(css2, { from: file2 }) + * root1.append(root2).toResult().css + * ``` + */ + parse: Parser + + /** + * Rehydrate a JSON AST (from `Node#toJSON`) back into the AST classes. + * + * ```js + * const json = root.toJSON() + * // save to file, send by network, etc + * const root2 = postcss.fromJSON(json) + * ``` + */ + fromJSON: JSONHydrator + + /** + * Contains the `list` module. + */ + list: List + + /** + * Creates a new `Comment` node. + * + * @param defaults Properties for the new node. + * @return New comment node + */ + comment(defaults?: CommentProps): Comment + + /** + * Creates a new `AtRule` node. + * + * @param defaults Properties for the new node. + * @return New at-rule node. + */ + atRule(defaults?: AtRuleProps): AtRule + + /** + * Creates a new `Declaration` node. + * + * @param defaults Properties for the new node. + * @return New declaration node. + */ + decl(defaults?: DeclarationProps): Declaration + + /** + * Creates a new `Rule` node. + * + * @param default Properties for the new node. + * @return New rule node. + */ + rule(defaults?: RuleProps): Rule + + /** + * Creates a new `Root` node. + * + * @param defaults Properties for the new node. + * @return New root node. + */ + root(defaults?: RootProps): Root + + /** + * Creates a new `Document` node. + * + * @param defaults Properties for the new node. + * @return New document node. + */ + document(defaults?: DocumentProps): Document + + CssSyntaxError: typeof CssSyntaxError + Declaration: typeof Declaration + Container: typeof Container + Comment: typeof Comment + Warning: typeof Warning + AtRule: typeof AtRule + Result: typeof Result + Input: typeof Input + Rule: typeof Rule + Root: typeof Root + Node: typeof Node +} + +export const stringify: Stringifier +export const parse: Parser +export const fromJSON: JSONHydrator + +export const comment: Postcss['comment'] +export const atRule: Postcss['atRule'] +export const decl: Postcss['decl'] +export const rule: Postcss['rule'] +export const root: Postcss['root'] + +declare const postcss: Postcss + +export default postcss diff --git a/node_modules/postcss/lib/postcss.js b/node_modules/postcss/lib/postcss.js new file mode 100644 index 0000000..080ee83 --- /dev/null +++ b/node_modules/postcss/lib/postcss.js @@ -0,0 +1,101 @@ +'use strict' + +let CssSyntaxError = require('./css-syntax-error') +let Declaration = require('./declaration') +let LazyResult = require('./lazy-result') +let Container = require('./container') +let Processor = require('./processor') +let stringify = require('./stringify') +let fromJSON = require('./fromJSON') +let Document = require('./document') +let Warning = require('./warning') +let Comment = require('./comment') +let AtRule = require('./at-rule') +let Result = require('./result.js') +let Input = require('./input') +let parse = require('./parse') +let list = require('./list') +let Rule = require('./rule') +let Root = require('./root') +let Node = require('./node') + +function postcss(...plugins) { + if (plugins.length === 1 && Array.isArray(plugins[0])) { + plugins = plugins[0] + } + return new Processor(plugins) +} + +postcss.plugin = function plugin(name, initializer) { + let warningPrinted = false + function creator(...args) { + // eslint-disable-next-line no-console + if (console && console.warn && !warningPrinted) { + warningPrinted = true + // eslint-disable-next-line no-console + console.warn( + name + + ': postcss.plugin was deprecated. Migration guide:\n' + + 'https://evilmartians.com/chronicles/postcss-8-plugin-migration' + ) + if (process.env.LANG && process.env.LANG.startsWith('cn')) { + /* c8 ignore next 7 */ + // eslint-disable-next-line no-console + console.warn( + name + + ': 里面 postcss.plugin 被弃用. 迁移指南:\n' + + 'https://www.w3ctech.com/topic/2226' + ) + } + } + let transformer = initializer(...args) + transformer.postcssPlugin = name + transformer.postcssVersion = new Processor().version + return transformer + } + + let cache + Object.defineProperty(creator, 'postcss', { + get() { + if (!cache) cache = creator() + return cache + } + }) + + creator.process = function (css, processOpts, pluginOpts) { + return postcss([creator(pluginOpts)]).process(css, processOpts) + } + + return creator +} + +postcss.stringify = stringify +postcss.parse = parse +postcss.fromJSON = fromJSON +postcss.list = list + +postcss.comment = defaults => new Comment(defaults) +postcss.atRule = defaults => new AtRule(defaults) +postcss.decl = defaults => new Declaration(defaults) +postcss.rule = defaults => new Rule(defaults) +postcss.root = defaults => new Root(defaults) +postcss.document = defaults => new Document(defaults) + +postcss.CssSyntaxError = CssSyntaxError +postcss.Declaration = Declaration +postcss.Container = Container +postcss.Processor = Processor +postcss.Document = Document +postcss.Comment = Comment +postcss.Warning = Warning +postcss.AtRule = AtRule +postcss.Result = Result +postcss.Input = Input +postcss.Rule = Rule +postcss.Root = Root +postcss.Node = Node + +LazyResult.registerPostcss(postcss) + +module.exports = postcss +postcss.default = postcss diff --git a/node_modules/postcss/lib/postcss.mjs b/node_modules/postcss/lib/postcss.mjs new file mode 100644 index 0000000..3507598 --- /dev/null +++ b/node_modules/postcss/lib/postcss.mjs @@ -0,0 +1,30 @@ +import postcss from './postcss.js' + +export default postcss + +export const stringify = postcss.stringify +export const fromJSON = postcss.fromJSON +export const plugin = postcss.plugin +export const parse = postcss.parse +export const list = postcss.list + +export const document = postcss.document +export const comment = postcss.comment +export const atRule = postcss.atRule +export const rule = postcss.rule +export const decl = postcss.decl +export const root = postcss.root + +export const CssSyntaxError = postcss.CssSyntaxError +export const Declaration = postcss.Declaration +export const Container = postcss.Container +export const Processor = postcss.Processor +export const Document = postcss.Document +export const Comment = postcss.Comment +export const Warning = postcss.Warning +export const AtRule = postcss.AtRule +export const Result = postcss.Result +export const Input = postcss.Input +export const Rule = postcss.Rule +export const Root = postcss.Root +export const Node = postcss.Node diff --git a/node_modules/postcss/lib/previous-map.d.ts b/node_modules/postcss/lib/previous-map.d.ts new file mode 100644 index 0000000..490d885 --- /dev/null +++ b/node_modules/postcss/lib/previous-map.d.ts @@ -0,0 +1,72 @@ +import { SourceMapConsumer } from 'source-map-js' + +import { ProcessOptions } from './postcss.js' + +/** + * Source map information from input CSS. + * For example, source map after Sass compiler. + * + * This class will automatically find source map in input CSS or in file system + * near input file (according `from` option). + * + * ```js + * const root = parse(css, { from: 'a.sass.css' }) + * root.input.map //=> PreviousMap + * ``` + */ +export default class PreviousMap { + /** + * Was source map inlined by data-uri to input CSS. + */ + inline: boolean + + /** + * `sourceMappingURL` content. + */ + annotation?: string + + /** + * Source map file content. + */ + text?: string + + /** + * The directory with source map file, if source map is in separated file. + */ + root?: string + + /** + * The CSS source identifier. Contains `Input#file` if the user + * set the `from` option, or `Input#id` if they did not. + */ + file?: string + + /** + * Path to source map file. + */ + mapFile?: string + + /** + * @param css Input CSS source. + * @param opts Process options. + */ + constructor(css: string, opts?: ProcessOptions) + + /** + * Create a instance of `SourceMapGenerator` class + * from the `source-map` library to work with source map information. + * + * It is lazy method, so it will create object only on first call + * and then it will use cache. + * + * @return Object with source map information. + */ + consumer(): SourceMapConsumer + + /** + * Does source map contains `sourcesContent` with input source text. + * + * @return Is `sourcesContent` present. + */ + withContent(): boolean +} diff --git a/node_modules/postcss/lib/previous-map.js b/node_modules/postcss/lib/previous-map.js new file mode 100644 index 0000000..d13a93a --- /dev/null +++ b/node_modules/postcss/lib/previous-map.js @@ -0,0 +1,142 @@ +'use strict' + +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { existsSync, readFileSync } = require('fs') +let { dirname, join } = require('path') + +function fromBase64(str) { + if (Buffer) { + return Buffer.from(str, 'base64').toString() + } else { + /* c8 ignore next 2 */ + return window.atob(str) + } +} + +class PreviousMap { + constructor(css, opts) { + if (opts.map === false) return + this.loadAnnotation(css) + this.inline = this.startWith(this.annotation, 'data:') + + let prev = opts.map ? opts.map.prev : undefined + let text = this.loadMap(opts.from, prev) + if (!this.mapFile && opts.from) { + this.mapFile = opts.from + } + if (this.mapFile) this.root = dirname(this.mapFile) + if (text) this.text = text + } + + consumer() { + if (!this.consumerCache) { + this.consumerCache = new SourceMapConsumer(this.text) + } + return this.consumerCache + } + + withContent() { + return !!( + this.consumer().sourcesContent && + this.consumer().sourcesContent.length > 0 + ) + } + + startWith(string, start) { + if (!string) return false + return string.substr(0, start.length) === start + } + + getAnnotationURL(sourceMapString) { + return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim() + } + + loadAnnotation(css) { + let comments = css.match(/\/\*\s*# sourceMappingURL=/gm) + if (!comments) return + + // sourceMappingURLs from comments, strings, etc. + let start = css.lastIndexOf(comments.pop()) + let end = css.indexOf('*/', start) + + if (start > -1 && end > -1) { + // Locate the last sourceMappingURL to avoid pickin + this.annotation = this.getAnnotationURL(css.substring(start, end)) + } + } + + decodeInline(text) { + let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/ + let baseUri = /^data:application\/json;base64,/ + let charsetUri = /^data:application\/json;charset=utf-?8,/ + let uri = /^data:application\/json,/ + + if (charsetUri.test(text) || uri.test(text)) { + return decodeURIComponent(text.substr(RegExp.lastMatch.length)) + } + + if (baseCharsetUri.test(text) || baseUri.test(text)) { + return fromBase64(text.substr(RegExp.lastMatch.length)) + } + + let encoding = text.match(/data:application\/json;([^,]+),/)[1] + throw new Error('Unsupported source map encoding ' + encoding) + } + + loadFile(path) { + this.root = dirname(path) + if (existsSync(path)) { + this.mapFile = path + return readFileSync(path, 'utf-8').toString().trim() + } + } + + loadMap(file, prev) { + if (prev === false) return false + + if (prev) { + if (typeof prev === 'string') { + return prev + } else if (typeof prev === 'function') { + let prevPath = prev(file) + if (prevPath) { + let map = this.loadFile(prevPath) + if (!map) { + throw new Error( + 'Unable to load previous source map: ' + prevPath.toString() + ) + } + return map + } + } else if (prev instanceof SourceMapConsumer) { + return SourceMapGenerator.fromSourceMap(prev).toString() + } else if (prev instanceof SourceMapGenerator) { + return prev.toString() + } else if (this.isMap(prev)) { + return JSON.stringify(prev) + } else { + throw new Error( + 'Unsupported previous source map format: ' + prev.toString() + ) + } + } else if (this.inline) { + return this.decodeInline(this.annotation) + } else if (this.annotation) { + let map = this.annotation + if (file) map = join(dirname(file), map) + return this.loadFile(map) + } + } + + isMap(map) { + if (typeof map !== 'object') return false + return ( + typeof map.mappings === 'string' || + typeof map._mappings === 'string' || + Array.isArray(map.sections) + ) + } +} + +module.exports = PreviousMap +PreviousMap.default = PreviousMap diff --git a/node_modules/postcss/lib/processor.d.ts b/node_modules/postcss/lib/processor.d.ts new file mode 100644 index 0000000..19a3653 --- /dev/null +++ b/node_modules/postcss/lib/processor.d.ts @@ -0,0 +1,102 @@ +import { + AcceptedPlugin, + Plugin, + ProcessOptions, + Transformer, + TransformCallback +} from './postcss.js' +import LazyResult from './lazy-result.js' +import Result from './result.js' +import Root from './root.js' +import NoWorkResult from './no-work-result.js' + +/** + * Contains plugins to process CSS. Create one `Processor` instance, + * initialize its plugins, and then use that instance on numerous CSS files. + * + * ```js + * const processor = postcss([autoprefixer, postcssNested]) + * processor.process(css1).then(result => console.log(result.css)) + * processor.process(css2).then(result => console.log(result.css)) + * ``` + */ +export default class Processor { + /** + * Current PostCSS version. + * + * ```js + * if (result.processor.version.split('.')[0] !== '6') { + * throw new Error('This plugin works only with PostCSS 6') + * } + * ``` + */ + version: string + + /** + * Plugins added to this processor. + * + * ```js + * const processor = postcss([autoprefixer, postcssNested]) + * processor.plugins.length //=> 2 + * ``` + */ + plugins: (Plugin | Transformer | TransformCallback)[] + + /** + * @param plugins PostCSS plugins + */ + constructor(plugins?: AcceptedPlugin[]) + + /** + * Adds a plugin to be used as a CSS processor. + * + * PostCSS plugin can be in 4 formats: + * * A plugin in `Plugin` format. + * * A plugin creator function with `pluginCreator.postcss = true`. + * PostCSS will call this function without argument to get plugin. + * * A function. PostCSS will pass the function a @{link Root} + * as the first argument and current `Result` instance + * as the second. + * * Another `Processor` instance. PostCSS will copy plugins + * from that instance into this one. + * + * Plugins can also be added by passing them as arguments when creating + * a `postcss` instance (see [`postcss(plugins)`]). + * + * Asynchronous plugins should return a `Promise` instance. + * + * ```js + * const processor = postcss() + * .use(autoprefixer) + * .use(postcssNested) + * ``` + * + * @param plugin PostCSS plugin or `Processor` with plugins. + * @return Current processor to make methods chain. + */ + use(plugin: AcceptedPlugin): this + + /** + * Parses source CSS and returns a `LazyResult` Promise proxy. + * Because some plugins can be asynchronous it doesn’t make + * any transformations. Transformations will be applied + * in the `LazyResult` methods. + * + * ```js + * processor.process(css, { from: 'a.css', to: 'a.out.css' }) + * .then(result => { + * console.log(result.css) + * }) + * ``` + * + * @param css String with input CSS or any object with a `toString()` method, + * like a Buffer. Optionally, senda `Result` instance + * and the processor will take the `Root` from it. + * @param opts Options. + * @return Promise proxy. + */ + process( + css: string | { toString(): string } | Result | LazyResult | Root, + options?: ProcessOptions + ): LazyResult | NoWorkResult +} diff --git a/node_modules/postcss/lib/processor.js b/node_modules/postcss/lib/processor.js new file mode 100644 index 0000000..409ebb6 --- /dev/null +++ b/node_modules/postcss/lib/processor.js @@ -0,0 +1,67 @@ +'use strict' + +let NoWorkResult = require('./no-work-result') +let LazyResult = require('./lazy-result') +let Document = require('./document') +let Root = require('./root') + +class Processor { + constructor(plugins = []) { + this.version = '8.4.21' + this.plugins = this.normalize(plugins) + } + + use(plugin) { + this.plugins = this.plugins.concat(this.normalize([plugin])) + return this + } + + process(css, opts = {}) { + if ( + this.plugins.length === 0 && + typeof opts.parser === 'undefined' && + typeof opts.stringifier === 'undefined' && + typeof opts.syntax === 'undefined' + ) { + return new NoWorkResult(this, css, opts) + } else { + return new LazyResult(this, css, opts) + } + } + + normalize(plugins) { + let normalized = [] + for (let i of plugins) { + if (i.postcss === true) { + i = i() + } else if (i.postcss) { + i = i.postcss + } + + if (typeof i === 'object' && Array.isArray(i.plugins)) { + normalized = normalized.concat(i.plugins) + } else if (typeof i === 'object' && i.postcssPlugin) { + normalized.push(i) + } else if (typeof i === 'function') { + normalized.push(i) + } else if (typeof i === 'object' && (i.parse || i.stringify)) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' + + 'one of the syntax/parser/stringifier options as outlined ' + + 'in your PostCSS runner documentation.' + ) + } + } else { + throw new Error(i + ' is not a PostCSS plugin') + } + } + return normalized + } +} + +module.exports = Processor +Processor.default = Processor + +Root.registerProcessor(Processor) +Document.registerProcessor(Processor) diff --git a/node_modules/postcss/lib/result.d.ts b/node_modules/postcss/lib/result.d.ts new file mode 100644 index 0000000..8a582b6 --- /dev/null +++ b/node_modules/postcss/lib/result.d.ts @@ -0,0 +1,196 @@ +import { + ProcessOptions, + Plugin, + SourceMap, + TransformCallback, + Root, + Document, + Node, + Warning, + WarningOptions +} from './postcss.js' +import Processor from './processor.js' + +export interface Message { + /** + * Message type. + */ + type: string + + /** + * Source PostCSS plugin name. + */ + plugin?: string + + [others: string]: any +} + +export interface ResultOptions extends ProcessOptions { + /** + * The CSS node that was the source of the warning. + */ + node?: Node + + /** + * Name of plugin that created this warning. `Result#warn` will fill it + * automatically with `Plugin#postcssPlugin` value. + */ + plugin?: string +} + +/** + * Provides the result of the PostCSS transformations. + * + * A Result instance is returned by `LazyResult#then` + * or `Root#toResult` methods. + * + * ```js + * postcss([autoprefixer]).process(css).then(result => { + * console.log(result.css) + * }) + * ``` + * + * ```js + * const result2 = postcss.parse(css).toResult() + * ``` + */ +export default class Result { + /** + * The Processor instance used for this transformation. + * + * ```js + * for (const plugin of result.processor.plugins) { + * if (plugin.postcssPlugin === 'postcss-bad') { + * throw 'postcss-good is incompatible with postcss-bad' + * } + * }) + * ``` + */ + processor: Processor + + /** + * Contains messages from plugins (e.g., warnings or custom messages). + * Each message should have type and plugin properties. + * + * ```js + * AtRule: { + * import: (atRule, { result }) { + * const importedFile = parseImport(atRule) + * result.messages.push({ + * type: 'dependency', + * plugin: 'postcss-import', + * file: importedFile, + * parent: result.opts.from + * }) + * } + * } + * ``` + */ + messages: Message[] + + /** + * Root node after all transformations. + * + * ```js + * root.toResult().root === root + * ``` + */ + root: Root | Document + + /** + * Options from the `Processor#process` or `Root#toResult` call + * that produced this Result instance.] + * + * ```js + * root.toResult(opts).opts === opts + * ``` + */ + opts: ResultOptions + + /** + * A CSS string representing of `Result#root`. + * + * ```js + * postcss.parse('a{}').toResult().css //=> "a{}" + * ``` + */ + css: string + + /** + * An instance of `SourceMapGenerator` class from the `source-map` library, + * representing changes to the `Result#root` instance. + * + * ```js + * result.map.toJSON() //=> { version: 3, file: 'a.css', … } + * ``` + * + * ```js + * if (result.map) { + * fs.writeFileSync(result.opts.to + '.map', result.map.toString()) + * } + * ``` + */ + map: SourceMap + + /** + * Last runned PostCSS plugin. + */ + lastPlugin: Plugin | TransformCallback + + /** + * @param processor Processor used for this transformation. + * @param root Root node after all transformations. + * @param opts Options from the `Processor#process` or `Root#toResult`. + */ + constructor(processor: Processor, root: Root | Document, opts: ResultOptions) + + /** + * An alias for the `Result#css` property. + * Use it with syntaxes that generate non-CSS output. + * + * ```js + * result.css === result.content + * ``` + */ + get content(): string + + /** + * Returns for `Result#css` content. + * + * ```js + * result + '' === result.css + * ``` + * + * @return String representing of `Result#root`. + */ + toString(): string + + /** + * Creates an instance of `Warning` and adds it to `Result#messages`. + * + * ```js + * if (decl.important) { + * result.warn('Avoid !important', { node: decl, word: '!important' }) + * } + * ``` + * + * @param text Warning message. + * @param opts Warning options. + * @return Created warning. + */ + warn(message: string, options?: WarningOptions): Warning + + /** + * Returns warnings from plugins. Filters `Warning` instances + * from `Result#messages`. + * + * ```js + * result.warnings().forEach(warn => { + * console.warn(warn.toString()) + * }) + * ``` + * + * @return Warnings from plugins. + */ + warnings(): Warning[] +} diff --git a/node_modules/postcss/lib/result.js b/node_modules/postcss/lib/result.js new file mode 100644 index 0000000..a39751d --- /dev/null +++ b/node_modules/postcss/lib/result.js @@ -0,0 +1,42 @@ +'use strict' + +let Warning = require('./warning') + +class Result { + constructor(processor, root, opts) { + this.processor = processor + this.messages = [] + this.root = root + this.opts = opts + this.css = undefined + this.map = undefined + } + + toString() { + return this.css + } + + warn(text, opts = {}) { + if (!opts.plugin) { + if (this.lastPlugin && this.lastPlugin.postcssPlugin) { + opts.plugin = this.lastPlugin.postcssPlugin + } + } + + let warning = new Warning(text, opts) + this.messages.push(warning) + + return warning + } + + warnings() { + return this.messages.filter(i => i.type === 'warning') + } + + get content() { + return this.css + } +} + +module.exports = Result +Result.default = Result diff --git a/node_modules/postcss/lib/root.d.ts b/node_modules/postcss/lib/root.d.ts new file mode 100644 index 0000000..251b92b --- /dev/null +++ b/node_modules/postcss/lib/root.d.ts @@ -0,0 +1,73 @@ +import Container, { ContainerProps } from './container.js' +import Document from './document.js' +import { ProcessOptions } from './postcss.js' +import Result from './result.js' + +interface RootRaws extends Record { + /** + * The space symbols after the last child to the end of file. + */ + after?: string + + /** + * Non-CSS code before `Root`, when `Root` is inside `Document`. + * + * **Experimental:** some aspects of this node could change within minor + * or patch version releases. + */ + codeBefore?: string + + /** + * Non-CSS code after `Root`, when `Root` is inside `Document`. + * + * **Experimental:** some aspects of this node could change within minor + * or patch version releases. + */ + codeAfter?: string + + /** + * Is the last child has an (optional) semicolon. + */ + semicolon?: boolean +} + +export interface RootProps extends ContainerProps { + /** + * Information used to generate byte-to-byte equal node string + * as it was in the origin input. + * */ + raws?: RootRaws +} + +/** + * Represents a CSS file and contains all its parsed nodes. + * + * ```js + * const root = postcss.parse('a{color:black} b{z-index:2}') + * root.type //=> 'root' + * root.nodes.length //=> 2 + * ``` + */ +export default class Root extends Container { + type: 'root' + parent: Document | undefined + raws: RootRaws + + /** + * Returns a `Result` instance representing the root’s CSS. + * + * ```js + * const root1 = postcss.parse(css1, { from: 'a.css' }) + * const root2 = postcss.parse(css2, { from: 'b.css' }) + * root1.append(root2) + * const result = root1.toResult({ to: 'all.css', map: true }) + * ``` + * + * @param opts Options. + * @return Result with current root’s CSS. + */ + toResult(options?: ProcessOptions): Result + + constructor(defaults?: RootProps) + assign(overrides: object | RootProps): this +} diff --git a/node_modules/postcss/lib/root.js b/node_modules/postcss/lib/root.js new file mode 100644 index 0000000..6f3dbb6 --- /dev/null +++ b/node_modules/postcss/lib/root.js @@ -0,0 +1,61 @@ +'use strict' + +let Container = require('./container') + +let LazyResult, Processor + +class Root extends Container { + constructor(defaults) { + super(defaults) + this.type = 'root' + if (!this.nodes) this.nodes = [] + } + + removeChild(child, ignore) { + let index = this.index(child) + + if (!ignore && index === 0 && this.nodes.length > 1) { + this.nodes[1].raws.before = this.nodes[index].raws.before + } + + return super.removeChild(child) + } + + normalize(child, sample, type) { + let nodes = super.normalize(child) + + if (sample) { + if (type === 'prepend') { + if (this.nodes.length > 1) { + sample.raws.before = this.nodes[1].raws.before + } else { + delete sample.raws.before + } + } else if (this.first !== sample) { + for (let node of nodes) { + node.raws.before = sample.raws.before + } + } + } + + return nodes + } + + toResult(opts = {}) { + let lazy = new LazyResult(new Processor(), this, opts) + return lazy.stringify() + } +} + +Root.registerLazyResult = dependant => { + LazyResult = dependant +} + +Root.registerProcessor = dependant => { + Processor = dependant +} + +module.exports = Root +Root.default = Root + +Container.registerRoot(Root) diff --git a/node_modules/postcss/lib/rule.d.ts b/node_modules/postcss/lib/rule.d.ts new file mode 100644 index 0000000..ad6abb5 --- /dev/null +++ b/node_modules/postcss/lib/rule.d.ts @@ -0,0 +1,104 @@ +import Container, { ContainerProps } from './container.js' + +interface RuleRaws extends Record { + /** + * The space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + */ + before?: string + + /** + * The space symbols after the last child of the node to the end of the node. + */ + after?: string + + /** + * The symbols between the selector and `{` for rules. + */ + between?: string + + /** + * Contains `true` if the last child has an (optional) semicolon. + */ + semicolon?: boolean + + /** + * Contains `true` if there is semicolon after rule. + */ + ownSemicolon?: string + + /** + * The rule’s selector with comments. + */ + selector?: { + value: string + raw: string + } +} + +export interface RuleProps extends ContainerProps { + /** Selector or selectors of the rule. */ + selector?: string + /** Selectors of the rule represented as an array of strings. */ + selectors?: string[] + /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ + raws?: RuleRaws +} + +/** + * Represents a CSS rule: a selector followed by a declaration block. + * + * ```js + * Once (root, { Rule }) { + * let a = new Rule({ selector: 'a' }) + * a.append(…) + * root.append(a) + * } + * ``` + * + * ```js + * const root = postcss.parse('a{}') + * const rule = root.first + * rule.type //=> 'rule' + * rule.toString() //=> 'a{}' + * ``` + */ +export default class Rule extends Container { + type: 'rule' + parent: Container | undefined + raws: RuleRaws + + /** + * The rule’s full selector represented as a string. + * + * ```js + * const root = postcss.parse('a, b { }') + * const rule = root.first + * rule.selector //=> 'a, b' + * ``` + */ + selector: string + + /** + * An array containing the rule’s individual selectors. + * Groups of selectors are split at commas. + * + * ```js + * const root = postcss.parse('a, b { }') + * const rule = root.first + * + * rule.selector //=> 'a, b' + * rule.selectors //=> ['a', 'b'] + * + * rule.selectors = ['a', 'strong'] + * rule.selector //=> 'a, strong' + * ``` + */ + selectors: string[] + + constructor(defaults?: RuleProps) + assign(overrides: object | RuleProps): this + clone(overrides?: Partial): this + cloneBefore(overrides?: Partial): this + cloneAfter(overrides?: Partial): this +} diff --git a/node_modules/postcss/lib/rule.js b/node_modules/postcss/lib/rule.js new file mode 100644 index 0000000..a93ab25 --- /dev/null +++ b/node_modules/postcss/lib/rule.js @@ -0,0 +1,27 @@ +'use strict' + +let Container = require('./container') +let list = require('./list') + +class Rule extends Container { + constructor(defaults) { + super(defaults) + this.type = 'rule' + if (!this.nodes) this.nodes = [] + } + + get selectors() { + return list.comma(this.selector) + } + + set selectors(values) { + let match = this.selector ? this.selector.match(/,\s*/) : null + let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen') + this.selector = values.join(sep) + } +} + +module.exports = Rule +Rule.default = Rule + +Container.registerRule(Rule) diff --git a/node_modules/postcss/lib/stringifier.d.ts b/node_modules/postcss/lib/stringifier.d.ts new file mode 100644 index 0000000..23289df --- /dev/null +++ b/node_modules/postcss/lib/stringifier.d.ts @@ -0,0 +1,37 @@ +import { + Document, + Root, + Comment, + Declaration, + Builder, + AnyNode, + Rule, + AtRule, + Container +} from './postcss.js' + +export default class Stringifier { + builder: Builder + constructor(builder: Builder) + stringify(node: AnyNode, semicolon?: boolean): void + document(node: Document): void + root(node: Root): void + comment(node: Comment): void + decl(node: Declaration, semicolon?: boolean): void + rule(node: Rule): void + atrule(node: AtRule, semicolon?: boolean): void + body(node: Container): void + block(node: AnyNode, start: string): void + raw(node: AnyNode, own: string | null, detect?: string): string + rawSemicolon(root: Root): boolean | undefined + rawEmptyBody(root: Root): string | undefined + rawIndent(root: Root): string | undefined + rawBeforeComment(root: Root, node: Comment): string | undefined + rawBeforeDecl(root: Root, node: Declaration): string | undefined + rawBeforeRule(root: Root): string | undefined + rawBeforeClose(root: Root): string | undefined + rawBeforeOpen(root: Root): string | undefined + rawColon(root: Root): string | undefined + beforeAfter(node: AnyNode, detect: 'before' | 'after'): string + rawValue(node: AnyNode, prop: string): string +} diff --git a/node_modules/postcss/lib/stringifier.js b/node_modules/postcss/lib/stringifier.js new file mode 100644 index 0000000..4065c47 --- /dev/null +++ b/node_modules/postcss/lib/stringifier.js @@ -0,0 +1,353 @@ +'use strict' + +const DEFAULT_RAW = { + colon: ': ', + indent: ' ', + beforeDecl: '\n', + beforeRule: '\n', + beforeOpen: ' ', + beforeClose: '\n', + beforeComment: '\n', + after: '\n', + emptyBody: '', + commentLeft: ' ', + commentRight: ' ', + semicolon: false +} + +function capitalize(str) { + return str[0].toUpperCase() + str.slice(1) +} + +class Stringifier { + constructor(builder) { + this.builder = builder + } + + stringify(node, semicolon) { + /* c8 ignore start */ + if (!this[node.type]) { + throw new Error( + 'Unknown AST node type ' + + node.type + + '. ' + + 'Maybe you need to change PostCSS stringifier.' + ) + } + /* c8 ignore stop */ + this[node.type](node, semicolon) + } + + document(node) { + this.body(node) + } + + root(node) { + this.body(node) + if (node.raws.after) this.builder(node.raws.after) + } + + comment(node) { + let left = this.raw(node, 'left', 'commentLeft') + let right = this.raw(node, 'right', 'commentRight') + this.builder('/*' + left + node.text + right + '*/', node) + } + + decl(node, semicolon) { + let between = this.raw(node, 'between', 'colon') + let string = node.prop + between + this.rawValue(node, 'value') + + if (node.important) { + string += node.raws.important || ' !important' + } + + if (semicolon) string += ';' + this.builder(string, node) + } + + rule(node) { + this.block(node, this.rawValue(node, 'selector')) + if (node.raws.ownSemicolon) { + this.builder(node.raws.ownSemicolon, node, 'end') + } + } + + atrule(node, semicolon) { + let name = '@' + node.name + let params = node.params ? this.rawValue(node, 'params') : '' + + if (typeof node.raws.afterName !== 'undefined') { + name += node.raws.afterName + } else if (params) { + name += ' ' + } + + if (node.nodes) { + this.block(node, name + params) + } else { + let end = (node.raws.between || '') + (semicolon ? ';' : '') + this.builder(name + params + end, node) + } + } + + body(node) { + let last = node.nodes.length - 1 + while (last > 0) { + if (node.nodes[last].type !== 'comment') break + last -= 1 + } + + let semicolon = this.raw(node, 'semicolon') + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i] + let before = this.raw(child, 'before') + if (before) this.builder(before) + this.stringify(child, last !== i || semicolon) + } + } + + block(node, start) { + let between = this.raw(node, 'between', 'beforeOpen') + this.builder(start + between + '{', node, 'start') + + let after + if (node.nodes && node.nodes.length) { + this.body(node) + after = this.raw(node, 'after') + } else { + after = this.raw(node, 'after', 'emptyBody') + } + + if (after) this.builder(after) + this.builder('}', node, 'end') + } + + raw(node, own, detect) { + let value + if (!detect) detect = own + + // Already had + if (own) { + value = node.raws[own] + if (typeof value !== 'undefined') return value + } + + let parent = node.parent + + if (detect === 'before') { + // Hack for first rule in CSS + if (!parent || (parent.type === 'root' && parent.first === node)) { + return '' + } + + // `root` nodes in `document` should use only their own raws + if (parent && parent.type === 'document') { + return '' + } + } + + // Floating child without parent + if (!parent) return DEFAULT_RAW[detect] + + // Detect style by other nodes + let root = node.root() + if (!root.rawCache) root.rawCache = {} + if (typeof root.rawCache[detect] !== 'undefined') { + return root.rawCache[detect] + } + + if (detect === 'before' || detect === 'after') { + return this.beforeAfter(node, detect) + } else { + let method = 'raw' + capitalize(detect) + if (this[method]) { + value = this[method](root, node) + } else { + root.walk(i => { + value = i.raws[own] + if (typeof value !== 'undefined') return false + }) + } + } + + if (typeof value === 'undefined') value = DEFAULT_RAW[detect] + + root.rawCache[detect] = value + return value + } + + rawSemicolon(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length && i.last.type === 'decl') { + value = i.raws.semicolon + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawEmptyBody(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length === 0) { + value = i.raws.after + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawIndent(root) { + if (root.raws.indent) return root.raws.indent + let value + root.walk(i => { + let p = i.parent + if (p && p !== root && p.parent && p.parent === root) { + if (typeof i.raws.before !== 'undefined') { + let parts = i.raws.before.split('\n') + value = parts[parts.length - 1] + value = value.replace(/\S/g, '') + return false + } + } + }) + return value + } + + rawBeforeComment(root, node) { + let value + root.walkComments(i => { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + }) + if (typeof value === 'undefined') { + value = this.raw(node, null, 'beforeDecl') + } else if (value) { + value = value.replace(/\S/g, '') + } + return value + } + + rawBeforeDecl(root, node) { + let value + root.walkDecls(i => { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + }) + if (typeof value === 'undefined') { + value = this.raw(node, null, 'beforeRule') + } else if (value) { + value = value.replace(/\S/g, '') + } + return value + } + + rawBeforeRule(root) { + let value + root.walk(i => { + if (i.nodes && (i.parent !== root || root.first !== i)) { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + } + }) + if (value) value = value.replace(/\S/g, '') + return value + } + + rawBeforeClose(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length > 0) { + if (typeof i.raws.after !== 'undefined') { + value = i.raws.after + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + } + }) + if (value) value = value.replace(/\S/g, '') + return value + } + + rawBeforeOpen(root) { + let value + root.walk(i => { + if (i.type !== 'decl') { + value = i.raws.between + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawColon(root) { + let value + root.walkDecls(i => { + if (typeof i.raws.between !== 'undefined') { + value = i.raws.between.replace(/[^\s:]/g, '') + return false + } + }) + return value + } + + beforeAfter(node, detect) { + let value + if (node.type === 'decl') { + value = this.raw(node, null, 'beforeDecl') + } else if (node.type === 'comment') { + value = this.raw(node, null, 'beforeComment') + } else if (detect === 'before') { + value = this.raw(node, null, 'beforeRule') + } else { + value = this.raw(node, null, 'beforeClose') + } + + let buf = node.parent + let depth = 0 + while (buf && buf.type !== 'root') { + depth += 1 + buf = buf.parent + } + + if (value.includes('\n')) { + let indent = this.raw(node, null, 'indent') + if (indent.length) { + for (let step = 0; step < depth; step++) value += indent + } + } + + return value + } + + rawValue(node, prop) { + let value = node[prop] + let raw = node.raws[prop] + if (raw && raw.value === value) { + return raw.raw + } + + return value + } +} + +module.exports = Stringifier +Stringifier.default = Stringifier diff --git a/node_modules/postcss/lib/stringify.d.ts b/node_modules/postcss/lib/stringify.d.ts new file mode 100644 index 0000000..363682f --- /dev/null +++ b/node_modules/postcss/lib/stringify.d.ts @@ -0,0 +1,5 @@ +import { Stringifier } from './postcss.js' + +declare const stringify: Stringifier + +export default stringify diff --git a/node_modules/postcss/lib/stringify.js b/node_modules/postcss/lib/stringify.js new file mode 100644 index 0000000..77bd017 --- /dev/null +++ b/node_modules/postcss/lib/stringify.js @@ -0,0 +1,11 @@ +'use strict' + +let Stringifier = require('./stringifier') + +function stringify(node, builder) { + let str = new Stringifier(builder) + str.stringify(node) +} + +module.exports = stringify +stringify.default = stringify diff --git a/node_modules/postcss/lib/symbols.js b/node_modules/postcss/lib/symbols.js new file mode 100644 index 0000000..a142c26 --- /dev/null +++ b/node_modules/postcss/lib/symbols.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports.isClean = Symbol('isClean') + +module.exports.my = Symbol('my') diff --git a/node_modules/postcss/lib/terminal-highlight.js b/node_modules/postcss/lib/terminal-highlight.js new file mode 100644 index 0000000..1f9f19e --- /dev/null +++ b/node_modules/postcss/lib/terminal-highlight.js @@ -0,0 +1,70 @@ +'use strict' + +let pico = require('picocolors') + +let tokenizer = require('./tokenize') + +let Input + +function registerInput(dependant) { + Input = dependant +} + +const HIGHLIGHT_THEME = { + 'brackets': pico.cyan, + 'at-word': pico.cyan, + 'comment': pico.gray, + 'string': pico.green, + 'class': pico.yellow, + 'hash': pico.magenta, + 'call': pico.cyan, + '(': pico.cyan, + ')': pico.cyan, + '{': pico.yellow, + '}': pico.yellow, + '[': pico.yellow, + ']': pico.yellow, + ':': pico.yellow, + ';': pico.yellow +} + +function getTokenType([type, value], processor) { + if (type === 'word') { + if (value[0] === '.') { + return 'class' + } + if (value[0] === '#') { + return 'hash' + } + } + + if (!processor.endOfFile()) { + let next = processor.nextToken() + processor.back(next) + if (next[0] === 'brackets' || next[0] === '(') return 'call' + } + + return type +} + +function terminalHighlight(css) { + let processor = tokenizer(new Input(css), { ignoreErrors: true }) + let result = '' + while (!processor.endOfFile()) { + let token = processor.nextToken() + let color = HIGHLIGHT_THEME[getTokenType(token, processor)] + if (color) { + result += token[1] + .split(/\r?\n/) + .map(i => color(i)) + .join('\n') + } else { + result += token[1] + } + } + return result +} + +terminalHighlight.registerInput = registerInput + +module.exports = terminalHighlight diff --git a/node_modules/postcss/lib/tokenize.js b/node_modules/postcss/lib/tokenize.js new file mode 100644 index 0000000..8dac706 --- /dev/null +++ b/node_modules/postcss/lib/tokenize.js @@ -0,0 +1,266 @@ +'use strict' + +const SINGLE_QUOTE = "'".charCodeAt(0) +const DOUBLE_QUOTE = '"'.charCodeAt(0) +const BACKSLASH = '\\'.charCodeAt(0) +const SLASH = '/'.charCodeAt(0) +const NEWLINE = '\n'.charCodeAt(0) +const SPACE = ' '.charCodeAt(0) +const FEED = '\f'.charCodeAt(0) +const TAB = '\t'.charCodeAt(0) +const CR = '\r'.charCodeAt(0) +const OPEN_SQUARE = '['.charCodeAt(0) +const CLOSE_SQUARE = ']'.charCodeAt(0) +const OPEN_PARENTHESES = '('.charCodeAt(0) +const CLOSE_PARENTHESES = ')'.charCodeAt(0) +const OPEN_CURLY = '{'.charCodeAt(0) +const CLOSE_CURLY = '}'.charCodeAt(0) +const SEMICOLON = ';'.charCodeAt(0) +const ASTERISK = '*'.charCodeAt(0) +const COLON = ':'.charCodeAt(0) +const AT = '@'.charCodeAt(0) + +const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g +const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g +const RE_BAD_BRACKET = /.[\n"'(/\\]/ +const RE_HEX_ESCAPE = /[\da-f]/i + +module.exports = function tokenizer(input, options = {}) { + let css = input.css.valueOf() + let ignore = options.ignoreErrors + + let code, next, quote, content, escape + let escaped, escapePos, prev, n, currentToken + + let length = css.length + let pos = 0 + let buffer = [] + let returned = [] + + function position() { + return pos + } + + function unclosed(what) { + throw input.error('Unclosed ' + what, pos) + } + + function endOfFile() { + return returned.length === 0 && pos >= length + } + + function nextToken(opts) { + if (returned.length) return returned.pop() + if (pos >= length) return + + let ignoreUnclosed = opts ? opts.ignoreUnclosed : false + + code = css.charCodeAt(pos) + + switch (code) { + case NEWLINE: + case SPACE: + case TAB: + case CR: + case FEED: { + next = pos + do { + next += 1 + code = css.charCodeAt(next) + } while ( + code === SPACE || + code === NEWLINE || + code === TAB || + code === CR || + code === FEED + ) + + currentToken = ['space', css.slice(pos, next)] + pos = next - 1 + break + } + + case OPEN_SQUARE: + case CLOSE_SQUARE: + case OPEN_CURLY: + case CLOSE_CURLY: + case COLON: + case SEMICOLON: + case CLOSE_PARENTHESES: { + let controlChar = String.fromCharCode(code) + currentToken = [controlChar, controlChar, pos] + break + } + + case OPEN_PARENTHESES: { + prev = buffer.length ? buffer.pop()[1] : '' + n = css.charCodeAt(pos + 1) + if ( + prev === 'url' && + n !== SINGLE_QUOTE && + n !== DOUBLE_QUOTE && + n !== SPACE && + n !== NEWLINE && + n !== TAB && + n !== FEED && + n !== CR + ) { + next = pos + do { + escaped = false + next = css.indexOf(')', next + 1) + if (next === -1) { + if (ignore || ignoreUnclosed) { + next = pos + break + } else { + unclosed('bracket') + } + } + escapePos = next + while (css.charCodeAt(escapePos - 1) === BACKSLASH) { + escapePos -= 1 + escaped = !escaped + } + } while (escaped) + + currentToken = ['brackets', css.slice(pos, next + 1), pos, next] + + pos = next + } else { + next = css.indexOf(')', pos + 1) + content = css.slice(pos, next + 1) + + if (next === -1 || RE_BAD_BRACKET.test(content)) { + currentToken = ['(', '(', pos] + } else { + currentToken = ['brackets', content, pos, next] + pos = next + } + } + + break + } + + case SINGLE_QUOTE: + case DOUBLE_QUOTE: { + quote = code === SINGLE_QUOTE ? "'" : '"' + next = pos + do { + escaped = false + next = css.indexOf(quote, next + 1) + if (next === -1) { + if (ignore || ignoreUnclosed) { + next = pos + 1 + break + } else { + unclosed('string') + } + } + escapePos = next + while (css.charCodeAt(escapePos - 1) === BACKSLASH) { + escapePos -= 1 + escaped = !escaped + } + } while (escaped) + + currentToken = ['string', css.slice(pos, next + 1), pos, next] + pos = next + break + } + + case AT: { + RE_AT_END.lastIndex = pos + 1 + RE_AT_END.test(css) + if (RE_AT_END.lastIndex === 0) { + next = css.length - 1 + } else { + next = RE_AT_END.lastIndex - 2 + } + + currentToken = ['at-word', css.slice(pos, next + 1), pos, next] + + pos = next + break + } + + case BACKSLASH: { + next = pos + escape = true + while (css.charCodeAt(next + 1) === BACKSLASH) { + next += 1 + escape = !escape + } + code = css.charCodeAt(next + 1) + if ( + escape && + code !== SLASH && + code !== SPACE && + code !== NEWLINE && + code !== TAB && + code !== CR && + code !== FEED + ) { + next += 1 + if (RE_HEX_ESCAPE.test(css.charAt(next))) { + while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) { + next += 1 + } + if (css.charCodeAt(next + 1) === SPACE) { + next += 1 + } + } + } + + currentToken = ['word', css.slice(pos, next + 1), pos, next] + + pos = next + break + } + + default: { + if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) { + next = css.indexOf('*/', pos + 2) + 1 + if (next === 0) { + if (ignore || ignoreUnclosed) { + next = css.length + } else { + unclosed('comment') + } + } + + currentToken = ['comment', css.slice(pos, next + 1), pos, next] + pos = next + } else { + RE_WORD_END.lastIndex = pos + 1 + RE_WORD_END.test(css) + if (RE_WORD_END.lastIndex === 0) { + next = css.length - 1 + } else { + next = RE_WORD_END.lastIndex - 2 + } + + currentToken = ['word', css.slice(pos, next + 1), pos, next] + buffer.push(currentToken) + pos = next + } + + break + } + } + + pos++ + return currentToken + } + + function back(token) { + returned.push(token) + } + + return { + back, + nextToken, + endOfFile, + position + } +} diff --git a/node_modules/postcss/lib/warn-once.js b/node_modules/postcss/lib/warn-once.js new file mode 100644 index 0000000..316e1cf --- /dev/null +++ b/node_modules/postcss/lib/warn-once.js @@ -0,0 +1,13 @@ +/* eslint-disable no-console */ +'use strict' + +let printed = {} + +module.exports = function warnOnce(message) { + if (printed[message]) return + printed[message] = true + + if (typeof console !== 'undefined' && console.warn) { + console.warn(message) + } +} diff --git a/node_modules/postcss/lib/warning.d.ts b/node_modules/postcss/lib/warning.d.ts new file mode 100644 index 0000000..838bef1 --- /dev/null +++ b/node_modules/postcss/lib/warning.d.ts @@ -0,0 +1,138 @@ +import { RangePosition } from './css-syntax-error.js' +import Node from './node.js' + +export interface WarningOptions { + /** + * CSS node that caused the warning. + */ + node?: Node + + /** + * Word in CSS source that caused the warning. + */ + word?: string + + /** + * Start index, inclusive, in CSS node string that caused the warning. + */ + index?: number + + /** + * End index, exclusive, in CSS node string that caused the warning. + */ + endIndex?: number + + /** + * Start position, inclusive, in CSS node string that caused the warning. + */ + start?: RangePosition + + /** + * End position, exclusive, in CSS node string that caused the warning. + */ + end?: RangePosition + + /** + * Name of the plugin that created this warning. `Result#warn` fills + * this property automatically. + */ + plugin?: string +} + +/** + * Represents a plugin’s warning. It can be created using `Node#warn`. + * + * ```js + * if (decl.important) { + * decl.warn(result, 'Avoid !important', { word: '!important' }) + * } + * ``` + */ +export default class Warning { + /** + * Type to filter warnings from `Result#messages`. + * Always equal to `"warning"`. + */ + type: 'warning' + + /** + * The warning message. + * + * ```js + * warning.text //=> 'Try to avoid !important' + * ``` + */ + text: string + + /** + * The name of the plugin that created this warning. + * When you call `Node#warn` it will fill this property automatically. + * + * ```js + * warning.plugin //=> 'postcss-important' + * ``` + */ + plugin: string + + /** + * Contains the CSS node that caused the warning. + * + * ```js + * warning.node.toString() //=> 'color: white !important' + * ``` + */ + node: Node + + /** + * Line for inclusive start position in the input file with this warning’s source. + * + * ```js + * warning.line //=> 5 + * ``` + */ + line: number + + /** + * Column for inclusive start position in the input file with this warning’s source. + * + * ```js + * warning.column //=> 6 + * ``` + */ + column: number + + /** + * Line for exclusive end position in the input file with this warning’s source. + * + * ```js + * warning.endLine //=> 6 + * ``` + */ + endLine?: number + + /** + * Column for exclusive end position in the input file with this warning’s source. + * + * ```js + * warning.endColumn //=> 4 + * ``` + */ + endColumn?: number + + /** + * @param text Warning message. + * @param opts Warning options. + */ + constructor(text: string, opts?: WarningOptions) + + /** + * Returns a warning position and message. + * + * ```js + * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important' + * ``` + * + * @return Warning position and message. + */ + toString(): string +} diff --git a/node_modules/postcss/lib/warning.js b/node_modules/postcss/lib/warning.js new file mode 100644 index 0000000..65aa525 --- /dev/null +++ b/node_modules/postcss/lib/warning.js @@ -0,0 +1,37 @@ +'use strict' + +class Warning { + constructor(text, opts = {}) { + this.type = 'warning' + this.text = text + + if (opts.node && opts.node.source) { + let range = opts.node.rangeBy(opts) + this.line = range.start.line + this.column = range.start.column + this.endLine = range.end.line + this.endColumn = range.end.column + } + + for (let opt in opts) this[opt] = opts[opt] + } + + toString() { + if (this.node) { + return this.node.error(this.text, { + plugin: this.plugin, + index: this.index, + word: this.word + }).message + } + + if (this.plugin) { + return this.plugin + ': ' + this.text + } + + return this.text + } +} + +module.exports = Warning +Warning.default = Warning diff --git a/node_modules/postcss/package.json b/node_modules/postcss/package.json new file mode 100755 index 0000000..8723a04 --- /dev/null +++ b/node_modules/postcss/package.json @@ -0,0 +1,85 @@ +{ + "name": "postcss", + "version": "8.4.21", + "description": "Tool for transforming styles with JS plugins", + "engines": { + "node": "^10 || ^12 || >=14" + }, + "exports": { + ".": { + "require": "./lib/postcss.js", + "import": "./lib/postcss.mjs", + "types": "./lib/postcss.d.ts" + }, + "./lib/at-rule": "./lib/at-rule.js", + "./lib/comment": "./lib/comment.js", + "./lib/container": "./lib/container.js", + "./lib/css-syntax-error": "./lib/css-syntax-error.js", + "./lib/declaration": "./lib/declaration.js", + "./lib/fromJSON": "./lib/fromJSON.js", + "./lib/input": "./lib/input.js", + "./lib/lazy-result": "./lib/lazy-result.js", + "./lib/no-work-result": "./lib/no-work-result.js", + "./lib/list": "./lib/list.js", + "./lib/map-generator": "./lib/map-generator.js", + "./lib/node": "./lib/node.js", + "./lib/parse": "./lib/parse.js", + "./lib/parser": "./lib/parser.js", + "./lib/postcss": "./lib/postcss.js", + "./lib/previous-map": "./lib/previous-map.js", + "./lib/processor": "./lib/processor.js", + "./lib/result": "./lib/result.js", + "./lib/root": "./lib/root.js", + "./lib/rule": "./lib/rule.js", + "./lib/stringifier": "./lib/stringifier.js", + "./lib/stringify": "./lib/stringify.js", + "./lib/symbols": "./lib/symbols.js", + "./lib/terminal-highlight": "./lib/terminal-highlight.js", + "./lib/tokenize": "./lib/tokenize.js", + "./lib/warn-once": "./lib/warn-once.js", + "./lib/warning": "./lib/warning.js", + "./package.json": "./package.json" + }, + "main": "./lib/postcss.js", + "types": "./lib/postcss.d.ts", + "keywords": [ + "css", + "postcss", + "rework", + "preprocessor", + "parser", + "source map", + "transform", + "manipulation", + "transpiler" + ], + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + } + ], + "author": "Andrey Sitnik ", + "license": "MIT", + "homepage": "https://postcss.org/", + "repository": "postcss/postcss", + "bugs": { + "url": "https://github.com/postcss/postcss/issues" + }, + "dependencies": { + "nanoid": "^3.3.4", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "browser": { + "./lib/terminal-highlight": false, + "source-map-js": false, + "path": false, + "url": false, + "fs": false + } +} diff --git a/node_modules/pretty-format/LICENSE b/node_modules/pretty-format/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/pretty-format/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +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/pretty-format/README.md b/node_modules/pretty-format/README.md new file mode 100755 index 0000000..c5cb004 --- /dev/null +++ b/node_modules/pretty-format/README.md @@ -0,0 +1,458 @@ +# pretty-format + +Stringify any JavaScript value. + +- Serialize built-in JavaScript types. +- Serialize application-specific data types with built-in or user-defined plugins. + +## Installation + +```sh +$ yarn add pretty-format +``` + +## Usage + +```js +const {format: prettyFormat} = require('pretty-format'); // CommonJS +``` + +```js +import {format as prettyFormat} from 'pretty-format'; // ES2015 modules +``` + +```js +const val = {object: {}}; +val.circularReference = val; +val[Symbol('foo')] = 'foo'; +val.map = new Map([['prop', 'value']]); +val.array = [-0, Infinity, NaN]; + +console.log(prettyFormat(val)); +/* +Object { + "array": Array [ + -0, + Infinity, + NaN, + ], + "circularReference": [Circular], + "map": Map { + "prop" => "value", + }, + "object": Object {}, + Symbol(foo): "foo", +} +*/ +``` + +## Usage with options + +```js +function onClick() {} + +console.log(prettyFormat(onClick)); +/* +[Function onClick] +*/ + +const options = { + printFunctionName: false, +}; +console.log(prettyFormat(onClick, options)); +/* +[Function] +*/ +``` + + +| key | type | default | description | +| :-------------------- | :-------- | :--------- | :------------------------------------------------------ | +| `callToJSON` | `boolean` | `true` | call `toJSON` method (if it exists) on objects | +| `compareKeys` | `function`| `undefined`| compare function used when sorting object keys | +| `escapeRegex` | `boolean` | `false` | escape special characters in regular expressions | +| `escapeString` | `boolean` | `true` | escape special characters in strings | +| `highlight` | `boolean` | `false` | highlight syntax with colors in terminal (some plugins) | +| `indent` | `number` | `2` | spaces in each level of indentation | +| `maxDepth` | `number` | `Infinity` | levels to print in arrays, objects, elements, and so on | +| `min` | `boolean` | `false` | minimize added space: no indentation nor line breaks | +| `plugins` | `array` | `[]` | plugins to serialize application-specific data types | +| `printBasicPrototype` | `boolean` | `false` | print the prototype for plain objects and arrays | +| `printFunctionName` | `boolean` | `true` | include or omit the name of a function | +| `theme` | `object` | | colors to highlight syntax in terminal | + +Property values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors) + +```js +const DEFAULT_THEME = { + comment: 'gray', + content: 'reset', + prop: 'yellow', + tag: 'cyan', + value: 'green', +}; +``` + +## Usage with plugins + +The `pretty-format` package provides some built-in plugins, including: + +- `ReactElement` for elements from `react` +- `ReactTestComponent` for test objects from `react-test-renderer` + +```js +// CommonJS +const React = require('react'); +const renderer = require('react-test-renderer'); +const {format: prettyFormat, plugins} = require('pretty-format'); + +const {ReactElement, ReactTestComponent} = plugins; +``` + +```js +// ES2015 modules and destructuring assignment +import React from 'react'; +import renderer from 'react-test-renderer'; +import {plugins, format as prettyFormat} from 'pretty-format'; + +const {ReactElement, ReactTestComponent} = plugins; +``` + +```js +const onClick = () => {}; +const element = React.createElement('button', {onClick}, 'Hello World'); + +const formatted1 = prettyFormat(element, { + plugins: [ReactElement], + printFunctionName: false, +}); +const formatted2 = prettyFormat(renderer.create(element).toJSON(), { + plugins: [ReactTestComponent], + printFunctionName: false, +}); +/* + +*/ +``` + +## Usage in Jest + +For snapshot tests, Jest uses `pretty-format` with options that include some of its built-in plugins. For this purpose, plugins are also known as **snapshot serializers**. + +To serialize application-specific data types, you can add modules to `devDependencies` of a project, and then: + +In an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration. + +```js +import serializer from 'my-serializer-module'; +expect.addSnapshotSerializer(serializer); + +// tests which have `expect(value).toMatchSnapshot()` assertions +``` + +For **all** test files, you can specify modules in Jest configuration. They precede built-in plugins for React, HTML, and Immutable.js data types. For example, in a `package.json` file: + +```json +{ + "jest": { + "snapshotSerializers": ["my-serializer-module"] + } +} +``` + +## Writing plugins + +A plugin is a JavaScript object. + +If `options` has a `plugins` array: for the first plugin whose `test(val)` method returns a truthy value, then `prettyFormat(val, options)` returns the result from either: + +- `serialize(val, …)` method of the **improved** interface (available in **version 21** or later) +- `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method) + +### test + +Write `test` so it can receive `val` argument of any type. To serialize **objects** which have certain properties, then a guarded expression like `val != null && …` or more concise `val && …` prevents the following errors: + +- `TypeError: Cannot read property 'whatever' of null` +- `TypeError: Cannot read property 'whatever' of undefined` + +For example, `test` method of built-in `ReactElement` plugin: + +```js +const elementSymbol = Symbol.for('react.element'); +const test = val => val && val.$$typeof === elementSymbol; +``` + +Pay attention to efficiency in `test` because `pretty-format` calls it often. + +### serialize + +The **improved** interface is available in **version 21** or later. + +Write `serialize` to return a string, given the arguments: + +- `val` which “passed the test” +- unchanging `config` object: derived from `options` +- current `indentation` string: concatenate to `indent` from `config` +- current `depth` number: compare to `maxDepth` from `config` +- current `refs` array: find circular references in objects +- `printer` callback function: serialize children + +### config + + +| key | type | description | +| :------------------ | :-------- | :------------------------------------------------------ | +| `callToJSON` | `boolean` | call `toJSON` method (if it exists) on objects | +| `compareKeys` | `function`| compare function used when sorting object keys | +| `colors` | `Object` | escape codes for colors to highlight syntax | +| `escapeRegex` | `boolean` | escape special characters in regular expressions | +| `escapeString` | `boolean` | escape special characters in strings | +| `indent` | `string` | spaces in each level of indentation | +| `maxDepth` | `number` | levels to print in arrays, objects, elements, and so on | +| `min` | `boolean` | minimize added space: no indentation nor line breaks | +| `plugins` | `array` | plugins to serialize application-specific data types | +| `printFunctionName` | `boolean` | include or omit the name of a function | +| `spacingInner` | `strong` | spacing to separate items in a list | +| `spacingOuter` | `strong` | spacing to enclose a list of items | + +Each property of `colors` in `config` corresponds to a property of `theme` in `options`: + +- the key is the same (for example, `tag`) +- the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`) + +Some properties in `config` are derived from `min` in `options`: + +- `spacingInner` and `spacingOuter` are **newline** if `min` is `false` +- `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true` + +### Example of serialize and test + +This plugin is a pattern you can apply to serialize composite data types. Side note: `pretty-format` does not need a plugin to serialize arrays. + +```js +// We reused more code when we factored out a function for child items +// that is independent of depth, name, and enclosing punctuation (see below). +const SEPARATOR = ','; +function serializeItems(items, config, indentation, depth, refs, printer) { + if (items.length === 0) { + return ''; + } + const indentationItems = indentation + config.indent; + return ( + config.spacingOuter + + items + .map( + item => + indentationItems + + printer(item, config, indentationItems, depth, refs), // callback + ) + .join(SEPARATOR + config.spacingInner) + + (config.min ? '' : SEPARATOR) + // following the last item + config.spacingOuter + + indentation + ); +} + +const plugin = { + test(val) { + return Array.isArray(val); + }, + serialize(array, config, indentation, depth, refs, printer) { + const name = array.constructor.name; + return ++depth > config.maxDepth + ? '[' + name + ']' + : (config.min ? '' : name + ' ') + + '[' + + serializeItems(array, config, indentation, depth, refs, printer) + + ']'; + }, +}; +``` + +```js +const val = { + filter: 'completed', + items: [ + { + text: 'Write test', + completed: true, + }, + { + text: 'Write serialize', + completed: true, + }, + ], +}; +``` + +```js +console.log( + prettyFormat(val, { + plugins: [plugin], + }), +); +/* +Object { + "filter": "completed", + "items": Array [ + Object { + "completed": true, + "text": "Write test", + }, + Object { + "completed": true, + "text": "Write serialize", + }, + ], +} +*/ +``` + +```js +console.log( + prettyFormat(val, { + indent: 4, + plugins: [plugin], + }), +); +/* +Object { + "filter": "completed", + "items": Array [ + Object { + "completed": true, + "text": "Write test", + }, + Object { + "completed": true, + "text": "Write serialize", + }, + ], +} +*/ +``` + +```js +console.log( + prettyFormat(val, { + maxDepth: 1, + plugins: [plugin], + }), +); +/* +Object { + "filter": "completed", + "items": [Array], +} +*/ +``` + +```js +console.log( + prettyFormat(val, { + min: true, + plugins: [plugin], + }), +); +/* +{"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]} +*/ +``` + +### print + +The **original** interface is adequate for plugins: + +- that **do not** depend on options other than `highlight` or `min` +- that **do not** depend on `depth` or `refs` in recursive traversal, and +- if values either + - do **not** require indentation, or + - do **not** occur as children of JavaScript data structures (for example, array) + +Write `print` to return a string, given the arguments: + +- `val` which “passed the test” +- current `printer(valChild)` callback function: serialize children +- current `indenter(lines)` callback function: indent lines at the next level +- unchanging `config` object: derived from `options` +- unchanging `colors` object: derived from `options` + +The 3 properties of `config` are `min` in `options` and: + +- `spacing` and `edgeSpacing` are **newline** if `min` is `false` +- `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true` + +Each property of `colors` corresponds to a property of `theme` in `options`: + +- the key is the same (for example, `tag`) +- the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`) + +### Example of print and test + +This plugin prints functions with the **number of named arguments** excluding rest argument. + +```js +const plugin = { + print(val) { + return `[Function ${val.name || 'anonymous'} ${val.length}]`; + }, + test(val) { + return typeof val === 'function'; + }, +}; +``` + +```js +const val = { + onClick(event) {}, + render() {}, +}; + +prettyFormat(val, { + plugins: [plugin], +}); +/* +Object { + "onClick": [Function onClick 1], + "render": [Function render 0], +} +*/ + +prettyFormat(val); +/* +Object { + "onClick": [Function onClick], + "render": [Function render], +} +*/ +``` + +This plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above. + +```js +prettyFormat(val, { + plugins: [pluginOld], + printFunctionName: false, +}); +/* +Object { + "onClick": [Function onClick 1], + "render": [Function render 0], +} +*/ + +prettyFormat(val, { + printFunctionName: false, +}); +/* +Object { + "onClick": [Function], + "render": [Function], +} +*/ +``` diff --git a/node_modules/pretty-format/build/collections.d.ts b/node_modules/pretty-format/build/collections.d.ts new file mode 100644 index 0000000..eaf7e61 --- /dev/null +++ b/node_modules/pretty-format/build/collections.d.ts @@ -0,0 +1,32 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +import type { Config, Printer, Refs } from './types'; +/** + * Return entries (for example, of a map) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ +export declare function printIteratorEntries(iterator: Iterator<[unknown, unknown]>, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, separator?: string): string; +/** + * Return values (for example, of a set) + * with spacing, indentation, and comma + * without surrounding punctuation (braces or brackets) + */ +export declare function printIteratorValues(iterator: Iterator, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer): string; +/** + * Return items (for example, of an array) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, brackets) + **/ +export declare function printListItems(list: ArrayLike, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer): string; +/** + * Return properties of an object + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ +export declare function printObjectProperties(val: Record, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer): string; diff --git a/node_modules/pretty-format/build/collections.js b/node_modules/pretty-format/build/collections.js new file mode 100644 index 0000000..004e349 --- /dev/null +++ b/node_modules/pretty-format/build/collections.js @@ -0,0 +1,187 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printIteratorEntries = printIteratorEntries; +exports.printIteratorValues = printIteratorValues; +exports.printListItems = printListItems; +exports.printObjectProperties = printObjectProperties; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +const getKeysOfEnumerableProperties = (object, compareKeys) => { + const keys = Object.keys(object).sort(compareKeys); + + if (Object.getOwnPropertySymbols) { + Object.getOwnPropertySymbols(object).forEach(symbol => { + if (Object.getOwnPropertyDescriptor(object, symbol).enumerable) { + keys.push(symbol); + } + }); + } + + return keys; +}; +/** + * Return entries (for example, of a map) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ + +function printIteratorEntries( + iterator, + config, + indentation, + depth, + refs, + printer, // Too bad, so sad that separator for ECMAScript Map has been ' => ' + // What a distracting diff if you change a data structure to/from + // ECMAScript Object or Immutable.Map/OrderedMap which use the default. + separator = ': ' +) { + let result = ''; + let current = iterator.next(); + + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + while (!current.done) { + const name = printer( + current.value[0], + config, + indentationNext, + depth, + refs + ); + const value = printer( + current.value[1], + config, + indentationNext, + depth, + refs + ); + result += indentationNext + name + separator + value; + current = iterator.next(); + + if (!current.done) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; +} +/** + * Return values (for example, of a set) + * with spacing, indentation, and comma + * without surrounding punctuation (braces or brackets) + */ + +function printIteratorValues( + iterator, + config, + indentation, + depth, + refs, + printer +) { + let result = ''; + let current = iterator.next(); + + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + while (!current.done) { + result += + indentationNext + + printer(current.value, config, indentationNext, depth, refs); + current = iterator.next(); + + if (!current.done) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; +} +/** + * Return items (for example, of an array) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, brackets) + **/ + +function printListItems(list, config, indentation, depth, refs, printer) { + let result = ''; + + if (list.length) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + for (let i = 0; i < list.length; i++) { + result += indentationNext; + + if (i in list) { + result += printer(list[i], config, indentationNext, depth, refs); + } + + if (i < list.length - 1) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; +} +/** + * Return properties of an object + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ + +function printObjectProperties(val, config, indentation, depth, refs, printer) { + let result = ''; + const keys = getKeysOfEnumerableProperties(val, config.compareKeys); + + if (keys.length) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const name = printer(key, config, indentationNext, depth, refs); + const value = printer(val[key], config, indentationNext, depth, refs); + result += indentationNext + name + ': ' + value; + + if (i < keys.length - 1) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; +} diff --git a/node_modules/pretty-format/build/index.d.ts b/node_modules/pretty-format/build/index.d.ts new file mode 100644 index 0000000..f62f82f --- /dev/null +++ b/node_modules/pretty-format/build/index.d.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type { NewPlugin, Options, OptionsReceived } from './types'; +export type { Colors, CompareKeys, Config, Options, OptionsReceived, OldPlugin, NewPlugin, Plugin, Plugins, PrettyFormatOptions, Printer, Refs, Theme, } from './types'; +export declare const DEFAULT_OPTIONS: Options; +/** + * Returns a presentation string of your `val` object + * @param val any potential JavaScript object + * @param options Custom settings + */ +export declare function format(val: unknown, options?: OptionsReceived): string; +export declare const plugins: { + AsymmetricMatcher: NewPlugin; + ConvertAnsi: NewPlugin; + DOMCollection: NewPlugin; + DOMElement: NewPlugin; + Immutable: NewPlugin; + ReactElement: NewPlugin; + ReactTestComponent: NewPlugin; +}; +export default format; diff --git a/node_modules/pretty-format/build/index.js b/node_modules/pretty-format/build/index.js new file mode 100644 index 0000000..9ebfa6f --- /dev/null +++ b/node_modules/pretty-format/build/index.js @@ -0,0 +1,597 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = exports.DEFAULT_OPTIONS = void 0; +exports.format = format; +exports.plugins = void 0; + +var _ansiStyles = _interopRequireDefault(require('ansi-styles')); + +var _collections = require('./collections'); + +var _AsymmetricMatcher = _interopRequireDefault( + require('./plugins/AsymmetricMatcher') +); + +var _ConvertAnsi = _interopRequireDefault(require('./plugins/ConvertAnsi')); + +var _DOMCollection = _interopRequireDefault(require('./plugins/DOMCollection')); + +var _DOMElement = _interopRequireDefault(require('./plugins/DOMElement')); + +var _Immutable = _interopRequireDefault(require('./plugins/Immutable')); + +var _ReactElement = _interopRequireDefault(require('./plugins/ReactElement')); + +var _ReactTestComponent = _interopRequireDefault( + require('./plugins/ReactTestComponent') +); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually */ +const toString = Object.prototype.toString; +const toISOString = Date.prototype.toISOString; +const errorToString = Error.prototype.toString; +const regExpToString = RegExp.prototype.toString; +/** + * Explicitly comparing typeof constructor to function avoids undefined as name + * when mock identity-obj-proxy returns the key as the value for any key. + */ + +const getConstructorName = val => + (typeof val.constructor === 'function' && val.constructor.name) || 'Object'; +/* global window */ + +/** Is val is equal to global window object? Works even if it does not exist :) */ + +const isWindow = val => typeof window !== 'undefined' && val === window; + +const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; +const NEWLINE_REGEXP = /\n/gi; + +class PrettyFormatPluginError extends Error { + constructor(message, stack) { + super(message); + this.stack = stack; + this.name = this.constructor.name; + } +} + +function isToStringedArrayType(toStringed) { + return ( + toStringed === '[object Array]' || + toStringed === '[object ArrayBuffer]' || + toStringed === '[object DataView]' || + toStringed === '[object Float32Array]' || + toStringed === '[object Float64Array]' || + toStringed === '[object Int8Array]' || + toStringed === '[object Int16Array]' || + toStringed === '[object Int32Array]' || + toStringed === '[object Uint8Array]' || + toStringed === '[object Uint8ClampedArray]' || + toStringed === '[object Uint16Array]' || + toStringed === '[object Uint32Array]' + ); +} + +function printNumber(val) { + return Object.is(val, -0) ? '-0' : String(val); +} + +function printBigInt(val) { + return String(`${val}n`); +} + +function printFunction(val, printFunctionName) { + if (!printFunctionName) { + return '[Function]'; + } + + return '[Function ' + (val.name || 'anonymous') + ']'; +} + +function printSymbol(val) { + return String(val).replace(SYMBOL_REGEXP, 'Symbol($1)'); +} + +function printError(val) { + return '[' + errorToString.call(val) + ']'; +} +/** + * The first port of call for printing an object, handles most of the + * data-types in JS. + */ + +function printBasicValue(val, printFunctionName, escapeRegex, escapeString) { + if (val === true || val === false) { + return '' + val; + } + + if (val === undefined) { + return 'undefined'; + } + + if (val === null) { + return 'null'; + } + + const typeOf = typeof val; + + if (typeOf === 'number') { + return printNumber(val); + } + + if (typeOf === 'bigint') { + return printBigInt(val); + } + + if (typeOf === 'string') { + if (escapeString) { + return '"' + val.replace(/"|\\/g, '\\$&') + '"'; + } + + return '"' + val + '"'; + } + + if (typeOf === 'function') { + return printFunction(val, printFunctionName); + } + + if (typeOf === 'symbol') { + return printSymbol(val); + } + + const toStringed = toString.call(val); + + if (toStringed === '[object WeakMap]') { + return 'WeakMap {}'; + } + + if (toStringed === '[object WeakSet]') { + return 'WeakSet {}'; + } + + if ( + toStringed === '[object Function]' || + toStringed === '[object GeneratorFunction]' + ) { + return printFunction(val, printFunctionName); + } + + if (toStringed === '[object Symbol]') { + return printSymbol(val); + } + + if (toStringed === '[object Date]') { + return isNaN(+val) ? 'Date { NaN }' : toISOString.call(val); + } + + if (toStringed === '[object Error]') { + return printError(val); + } + + if (toStringed === '[object RegExp]') { + if (escapeRegex) { + // https://github.com/benjamingr/RegExp.escape/blob/main/polyfill.js + return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); + } + + return regExpToString.call(val); + } + + if (val instanceof Error) { + return printError(val); + } + + return null; +} +/** + * Handles more complex objects ( such as objects with circular references. + * maps and sets etc ) + */ + +function printComplexValue( + val, + config, + indentation, + depth, + refs, + hasCalledToJSON +) { + if (refs.indexOf(val) !== -1) { + return '[Circular]'; + } + + refs = refs.slice(); + refs.push(val); + const hitMaxDepth = ++depth > config.maxDepth; + const min = config.min; + + if ( + config.callToJSON && + !hitMaxDepth && + val.toJSON && + typeof val.toJSON === 'function' && + !hasCalledToJSON + ) { + return printer(val.toJSON(), config, indentation, depth, refs, true); + } + + const toStringed = toString.call(val); + + if (toStringed === '[object Arguments]') { + return hitMaxDepth + ? '[Arguments]' + : (min ? '' : 'Arguments ') + + '[' + + (0, _collections.printListItems)( + val, + config, + indentation, + depth, + refs, + printer + ) + + ']'; + } + + if (isToStringedArrayType(toStringed)) { + return hitMaxDepth + ? '[' + val.constructor.name + ']' + : (min + ? '' + : !config.printBasicPrototype && val.constructor.name === 'Array' + ? '' + : val.constructor.name + ' ') + + '[' + + (0, _collections.printListItems)( + val, + config, + indentation, + depth, + refs, + printer + ) + + ']'; + } + + if (toStringed === '[object Map]') { + return hitMaxDepth + ? '[Map]' + : 'Map {' + + (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer, + ' => ' + ) + + '}'; + } + + if (toStringed === '[object Set]') { + return hitMaxDepth + ? '[Set]' + : 'Set {' + + (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + + '}'; + } // Avoid failure to serialize global window object in jsdom test environment. + // For example, not even relevant if window is prop of React element. + + return hitMaxDepth || isWindow(val) + ? '[' + getConstructorName(val) + ']' + : (min + ? '' + : !config.printBasicPrototype && getConstructorName(val) === 'Object' + ? '' + : getConstructorName(val) + ' ') + + '{' + + (0, _collections.printObjectProperties)( + val, + config, + indentation, + depth, + refs, + printer + ) + + '}'; +} + +function isNewPlugin(plugin) { + return plugin.serialize != null; +} + +function printPlugin(plugin, val, config, indentation, depth, refs) { + let printed; + + try { + printed = isNewPlugin(plugin) + ? plugin.serialize(val, config, indentation, depth, refs, printer) + : plugin.print( + val, + valChild => printer(valChild, config, indentation, depth, refs), + str => { + const indentationNext = indentation + config.indent; + return ( + indentationNext + + str.replace(NEWLINE_REGEXP, '\n' + indentationNext) + ); + }, + { + edgeSpacing: config.spacingOuter, + min: config.min, + spacing: config.spacingInner + }, + config.colors + ); + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + + if (typeof printed !== 'string') { + throw new Error( + `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".` + ); + } + + return printed; +} + +function findPlugin(plugins, val) { + for (let p = 0; p < plugins.length; p++) { + try { + if (plugins[p].test(val)) { + return plugins[p]; + } + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + } + + return null; +} + +function printer(val, config, indentation, depth, refs, hasCalledToJSON) { + const plugin = findPlugin(config.plugins, val); + + if (plugin !== null) { + return printPlugin(plugin, val, config, indentation, depth, refs); + } + + const basicResult = printBasicValue( + val, + config.printFunctionName, + config.escapeRegex, + config.escapeString + ); + + if (basicResult !== null) { + return basicResult; + } + + return printComplexValue( + val, + config, + indentation, + depth, + refs, + hasCalledToJSON + ); +} + +const DEFAULT_THEME = { + comment: 'gray', + content: 'reset', + prop: 'yellow', + tag: 'cyan', + value: 'green' +}; +const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); +const DEFAULT_OPTIONS = { + callToJSON: true, + compareKeys: undefined, + escapeRegex: false, + escapeString: true, + highlight: false, + indent: 2, + maxDepth: Infinity, + min: false, + plugins: [], + printBasicPrototype: true, + printFunctionName: true, + theme: DEFAULT_THEME +}; +exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS; + +function validateOptions(options) { + Object.keys(options).forEach(key => { + if (!DEFAULT_OPTIONS.hasOwnProperty(key)) { + throw new Error(`pretty-format: Unknown option "${key}".`); + } + }); + + if (options.min && options.indent !== undefined && options.indent !== 0) { + throw new Error( + 'pretty-format: Options "min" and "indent" cannot be used together.' + ); + } + + if (options.theme !== undefined) { + if (options.theme === null) { + throw new Error('pretty-format: Option "theme" must not be null.'); + } + + if (typeof options.theme !== 'object') { + throw new Error( + `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".` + ); + } + } +} + +const getColorsHighlight = options => + DEFAULT_THEME_KEYS.reduce((colors, key) => { + const value = + options.theme && options.theme[key] !== undefined + ? options.theme[key] + : DEFAULT_THEME[key]; + const color = value && _ansiStyles.default[value]; + + if ( + color && + typeof color.close === 'string' && + typeof color.open === 'string' + ) { + colors[key] = color; + } else { + throw new Error( + `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.` + ); + } + + return colors; + }, Object.create(null)); + +const getColorsEmpty = () => + DEFAULT_THEME_KEYS.reduce((colors, key) => { + colors[key] = { + close: '', + open: '' + }; + return colors; + }, Object.create(null)); + +const getPrintFunctionName = options => + options && options.printFunctionName !== undefined + ? options.printFunctionName + : DEFAULT_OPTIONS.printFunctionName; + +const getEscapeRegex = options => + options && options.escapeRegex !== undefined + ? options.escapeRegex + : DEFAULT_OPTIONS.escapeRegex; + +const getEscapeString = options => + options && options.escapeString !== undefined + ? options.escapeString + : DEFAULT_OPTIONS.escapeString; + +const getConfig = options => { + var _options$printBasicPr; + + return { + callToJSON: + options && options.callToJSON !== undefined + ? options.callToJSON + : DEFAULT_OPTIONS.callToJSON, + colors: + options && options.highlight + ? getColorsHighlight(options) + : getColorsEmpty(), + compareKeys: + options && typeof options.compareKeys === 'function' + ? options.compareKeys + : DEFAULT_OPTIONS.compareKeys, + escapeRegex: getEscapeRegex(options), + escapeString: getEscapeString(options), + indent: + options && options.min + ? '' + : createIndent( + options && options.indent !== undefined + ? options.indent + : DEFAULT_OPTIONS.indent + ), + maxDepth: + options && options.maxDepth !== undefined + ? options.maxDepth + : DEFAULT_OPTIONS.maxDepth, + min: + options && options.min !== undefined ? options.min : DEFAULT_OPTIONS.min, + plugins: + options && options.plugins !== undefined + ? options.plugins + : DEFAULT_OPTIONS.plugins, + printBasicPrototype: + (_options$printBasicPr = + options === null || options === void 0 + ? void 0 + : options.printBasicPrototype) !== null && + _options$printBasicPr !== void 0 + ? _options$printBasicPr + : true, + printFunctionName: getPrintFunctionName(options), + spacingInner: options && options.min ? ' ' : '\n', + spacingOuter: options && options.min ? '' : '\n' + }; +}; + +function createIndent(indent) { + return new Array(indent + 1).join(' '); +} +/** + * Returns a presentation string of your `val` object + * @param val any potential JavaScript object + * @param options Custom settings + */ + +function format(val, options) { + if (options) { + validateOptions(options); + + if (options.plugins) { + const plugin = findPlugin(options.plugins, val); + + if (plugin !== null) { + return printPlugin(plugin, val, getConfig(options), '', 0, []); + } + } + } + + const basicResult = printBasicValue( + val, + getPrintFunctionName(options), + getEscapeRegex(options), + getEscapeString(options) + ); + + if (basicResult !== null) { + return basicResult; + } + + return printComplexValue(val, getConfig(options), '', 0, []); +} + +const plugins = { + AsymmetricMatcher: _AsymmetricMatcher.default, + ConvertAnsi: _ConvertAnsi.default, + DOMCollection: _DOMCollection.default, + DOMElement: _DOMElement.default, + Immutable: _Immutable.default, + ReactElement: _ReactElement.default, + ReactTestComponent: _ReactTestComponent.default +}; +exports.plugins = plugins; +var _default = format; +exports.default = _default; diff --git a/node_modules/pretty-format/build/plugins/AsymmetricMatcher.d.ts b/node_modules/pretty-format/build/plugins/AsymmetricMatcher.d.ts new file mode 100644 index 0000000..fd2531b --- /dev/null +++ b/node_modules/pretty-format/build/plugins/AsymmetricMatcher.d.ts @@ -0,0 +1,11 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type { NewPlugin } from '../types'; +export declare const serialize: NewPlugin['serialize']; +export declare const test: NewPlugin['test']; +declare const plugin: NewPlugin; +export default plugin; diff --git a/node_modules/pretty-format/build/plugins/AsymmetricMatcher.js b/node_modules/pretty-format/build/plugins/AsymmetricMatcher.js new file mode 100644 index 0000000..4003451 --- /dev/null +++ b/node_modules/pretty-format/build/plugins/AsymmetricMatcher.js @@ -0,0 +1,117 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; + +var _collections = require('../collections'); + +var global = (function () { + if (typeof globalThis !== 'undefined') { + return globalThis; + } else if (typeof global !== 'undefined') { + return global; + } else if (typeof self !== 'undefined') { + return self; + } else if (typeof window !== 'undefined') { + return window; + } else { + return Function('return this')(); + } +})(); + +var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol; +const asymmetricMatcher = + typeof Symbol === 'function' && Symbol.for + ? Symbol.for('jest.asymmetricMatcher') + : 0x1357a5; +const SPACE = ' '; + +const serialize = (val, config, indentation, depth, refs, printer) => { + const stringedValue = val.toString(); + + if ( + stringedValue === 'ArrayContaining' || + stringedValue === 'ArrayNotContaining' + ) { + if (++depth > config.maxDepth) { + return '[' + stringedValue + ']'; + } + + return ( + stringedValue + + SPACE + + '[' + + (0, _collections.printListItems)( + val.sample, + config, + indentation, + depth, + refs, + printer + ) + + ']' + ); + } + + if ( + stringedValue === 'ObjectContaining' || + stringedValue === 'ObjectNotContaining' + ) { + if (++depth > config.maxDepth) { + return '[' + stringedValue + ']'; + } + + return ( + stringedValue + + SPACE + + '{' + + (0, _collections.printObjectProperties)( + val.sample, + config, + indentation, + depth, + refs, + printer + ) + + '}' + ); + } + + if ( + stringedValue === 'StringMatching' || + stringedValue === 'StringNotMatching' + ) { + return ( + stringedValue + + SPACE + + printer(val.sample, config, indentation, depth, refs) + ); + } + + if ( + stringedValue === 'StringContaining' || + stringedValue === 'StringNotContaining' + ) { + return ( + stringedValue + + SPACE + + printer(val.sample, config, indentation, depth, refs) + ); + } + + return val.toAsymmetricMatcher(); +}; + +exports.serialize = serialize; + +const test = val => val && val.$$typeof === asymmetricMatcher; + +exports.test = test; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/node_modules/pretty-format/build/plugins/ConvertAnsi.d.ts b/node_modules/pretty-format/build/plugins/ConvertAnsi.d.ts new file mode 100644 index 0000000..bb0f507 --- /dev/null +++ b/node_modules/pretty-format/build/plugins/ConvertAnsi.d.ts @@ -0,0 +1,11 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type { NewPlugin } from '../types'; +export declare const test: NewPlugin['test']; +export declare const serialize: NewPlugin['serialize']; +declare const plugin: NewPlugin; +export default plugin; diff --git a/node_modules/pretty-format/build/plugins/ConvertAnsi.js b/node_modules/pretty-format/build/plugins/ConvertAnsi.js new file mode 100644 index 0000000..c5edf00 --- /dev/null +++ b/node_modules/pretty-format/build/plugins/ConvertAnsi.js @@ -0,0 +1,96 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; + +var _ansiRegex = _interopRequireDefault(require('ansi-regex')); + +var _ansiStyles = _interopRequireDefault(require('ansi-styles')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const toHumanReadableAnsi = text => + text.replace((0, _ansiRegex.default)(), match => { + switch (match) { + case _ansiStyles.default.red.close: + case _ansiStyles.default.green.close: + case _ansiStyles.default.cyan.close: + case _ansiStyles.default.gray.close: + case _ansiStyles.default.white.close: + case _ansiStyles.default.yellow.close: + case _ansiStyles.default.bgRed.close: + case _ansiStyles.default.bgGreen.close: + case _ansiStyles.default.bgYellow.close: + case _ansiStyles.default.inverse.close: + case _ansiStyles.default.dim.close: + case _ansiStyles.default.bold.close: + case _ansiStyles.default.reset.open: + case _ansiStyles.default.reset.close: + return ''; + + case _ansiStyles.default.red.open: + return ''; + + case _ansiStyles.default.green.open: + return ''; + + case _ansiStyles.default.cyan.open: + return ''; + + case _ansiStyles.default.gray.open: + return ''; + + case _ansiStyles.default.white.open: + return ''; + + case _ansiStyles.default.yellow.open: + return ''; + + case _ansiStyles.default.bgRed.open: + return ''; + + case _ansiStyles.default.bgGreen.open: + return ''; + + case _ansiStyles.default.bgYellow.open: + return ''; + + case _ansiStyles.default.inverse.open: + return ''; + + case _ansiStyles.default.dim.open: + return ''; + + case _ansiStyles.default.bold.open: + return ''; + + default: + return ''; + } + }); + +const test = val => + typeof val === 'string' && !!val.match((0, _ansiRegex.default)()); + +exports.test = test; + +const serialize = (val, config, indentation, depth, refs, printer) => + printer(toHumanReadableAnsi(val), config, indentation, depth, refs); + +exports.serialize = serialize; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/node_modules/pretty-format/build/plugins/DOMCollection.d.ts b/node_modules/pretty-format/build/plugins/DOMCollection.d.ts new file mode 100644 index 0000000..bb0f507 --- /dev/null +++ b/node_modules/pretty-format/build/plugins/DOMCollection.d.ts @@ -0,0 +1,11 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type { NewPlugin } from '../types'; +export declare const test: NewPlugin['test']; +export declare const serialize: NewPlugin['serialize']; +declare const plugin: NewPlugin; +export default plugin; diff --git a/node_modules/pretty-format/build/plugins/DOMCollection.js b/node_modules/pretty-format/build/plugins/DOMCollection.js new file mode 100644 index 0000000..f3dba3d --- /dev/null +++ b/node_modules/pretty-format/build/plugins/DOMCollection.js @@ -0,0 +1,80 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; + +var _collections = require('../collections'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually */ +const SPACE = ' '; +const OBJECT_NAMES = ['DOMStringMap', 'NamedNodeMap']; +const ARRAY_REGEXP = /^(HTML\w*Collection|NodeList)$/; + +const testName = name => + OBJECT_NAMES.indexOf(name) !== -1 || ARRAY_REGEXP.test(name); + +const test = val => + val && + val.constructor && + !!val.constructor.name && + testName(val.constructor.name); + +exports.test = test; + +const isNamedNodeMap = collection => + collection.constructor.name === 'NamedNodeMap'; + +const serialize = (collection, config, indentation, depth, refs, printer) => { + const name = collection.constructor.name; + + if (++depth > config.maxDepth) { + return '[' + name + ']'; + } + + return ( + (config.min ? '' : name + SPACE) + + (OBJECT_NAMES.indexOf(name) !== -1 + ? '{' + + (0, _collections.printObjectProperties)( + isNamedNodeMap(collection) + ? Array.from(collection).reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}) + : {...collection}, + config, + indentation, + depth, + refs, + printer + ) + + '}' + : '[' + + (0, _collections.printListItems)( + Array.from(collection), + config, + indentation, + depth, + refs, + printer + ) + + ']') + ); +}; + +exports.serialize = serialize; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/node_modules/pretty-format/build/plugins/DOMElement.d.ts b/node_modules/pretty-format/build/plugins/DOMElement.d.ts new file mode 100644 index 0000000..bb0f507 --- /dev/null +++ b/node_modules/pretty-format/build/plugins/DOMElement.d.ts @@ -0,0 +1,11 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type { NewPlugin } from '../types'; +export declare const test: NewPlugin['test']; +export declare const serialize: NewPlugin['serialize']; +declare const plugin: NewPlugin; +export default plugin; diff --git a/node_modules/pretty-format/build/plugins/DOMElement.js b/node_modules/pretty-format/build/plugins/DOMElement.js new file mode 100644 index 0000000..b9d30ce --- /dev/null +++ b/node_modules/pretty-format/build/plugins/DOMElement.js @@ -0,0 +1,128 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; + +var _markup = require('./lib/markup'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const ELEMENT_NODE = 1; +const TEXT_NODE = 3; +const COMMENT_NODE = 8; +const FRAGMENT_NODE = 11; +const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; + +const testHasAttribute = val => { + try { + return typeof val.hasAttribute === 'function' && val.hasAttribute('is'); + } catch { + return false; + } +}; + +const testNode = val => { + const constructorName = val.constructor.name; + const {nodeType, tagName} = val; + const isCustomElement = + (typeof tagName === 'string' && tagName.includes('-')) || + testHasAttribute(val); + return ( + (nodeType === ELEMENT_NODE && + (ELEMENT_REGEXP.test(constructorName) || isCustomElement)) || + (nodeType === TEXT_NODE && constructorName === 'Text') || + (nodeType === COMMENT_NODE && constructorName === 'Comment') || + (nodeType === FRAGMENT_NODE && constructorName === 'DocumentFragment') + ); +}; + +const test = val => { + var _val$constructor; + + return ( + (val === null || val === void 0 + ? void 0 + : (_val$constructor = val.constructor) === null || + _val$constructor === void 0 + ? void 0 + : _val$constructor.name) && testNode(val) + ); +}; + +exports.test = test; + +function nodeIsText(node) { + return node.nodeType === TEXT_NODE; +} + +function nodeIsComment(node) { + return node.nodeType === COMMENT_NODE; +} + +function nodeIsFragment(node) { + return node.nodeType === FRAGMENT_NODE; +} + +const serialize = (node, config, indentation, depth, refs, printer) => { + if (nodeIsText(node)) { + return (0, _markup.printText)(node.data, config); + } + + if (nodeIsComment(node)) { + return (0, _markup.printComment)(node.data, config); + } + + const type = nodeIsFragment(node) + ? 'DocumentFragment' + : node.tagName.toLowerCase(); + + if (++depth > config.maxDepth) { + return (0, _markup.printElementAsLeaf)(type, config); + } + + return (0, _markup.printElement)( + type, + (0, _markup.printProps)( + nodeIsFragment(node) + ? [] + : Array.from(node.attributes) + .map(attr => attr.name) + .sort(), + nodeIsFragment(node) + ? {} + : Array.from(node.attributes).reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}), + config, + indentation + config.indent, + depth, + refs, + printer + ), + (0, _markup.printChildren)( + Array.prototype.slice.call(node.childNodes || node.children), + config, + indentation + config.indent, + depth, + refs, + printer + ), + config, + indentation + ); +}; + +exports.serialize = serialize; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/node_modules/pretty-format/build/plugins/Immutable.d.ts b/node_modules/pretty-format/build/plugins/Immutable.d.ts new file mode 100644 index 0000000..fd2531b --- /dev/null +++ b/node_modules/pretty-format/build/plugins/Immutable.d.ts @@ -0,0 +1,11 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type { NewPlugin } from '../types'; +export declare const serialize: NewPlugin['serialize']; +export declare const test: NewPlugin['test']; +declare const plugin: NewPlugin; +export default plugin; diff --git a/node_modules/pretty-format/build/plugins/Immutable.js b/node_modules/pretty-format/build/plugins/Immutable.js new file mode 100644 index 0000000..9915966 --- /dev/null +++ b/node_modules/pretty-format/build/plugins/Immutable.js @@ -0,0 +1,247 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; + +var _collections = require('../collections'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// SENTINEL constants are from https://github.com/facebook/immutable-js +const IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; +const IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; +const IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; +const IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; +const IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; +const IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@'; // immutable v4 + +const IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; +const IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; +const IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; + +const getImmutableName = name => 'Immutable.' + name; + +const printAsLeaf = name => '[' + name + ']'; + +const SPACE = ' '; +const LAZY = '…'; // Seq is lazy if it calls a method like filter + +const printImmutableEntries = ( + val, + config, + indentation, + depth, + refs, + printer, + type +) => + ++depth > config.maxDepth + ? printAsLeaf(getImmutableName(type)) + : getImmutableName(type) + + SPACE + + '{' + + (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer + ) + + '}'; // Record has an entries method because it is a collection in immutable v3. +// Return an iterator for Immutable Record from version v3 or v4. + +function getRecordEntries(val) { + let i = 0; + return { + next() { + if (i < val._keys.length) { + const key = val._keys[i++]; + return { + done: false, + value: [key, val.get(key)] + }; + } + + return { + done: true, + value: undefined + }; + } + }; +} + +const printImmutableRecord = ( + val, + config, + indentation, + depth, + refs, + printer +) => { + // _name property is defined only for an Immutable Record instance + // which was constructed with a second optional descriptive name arg + const name = getImmutableName(val._name || 'Record'); + return ++depth > config.maxDepth + ? printAsLeaf(name) + : name + + SPACE + + '{' + + (0, _collections.printIteratorEntries)( + getRecordEntries(val), + config, + indentation, + depth, + refs, + printer + ) + + '}'; +}; + +const printImmutableSeq = (val, config, indentation, depth, refs, printer) => { + const name = getImmutableName('Seq'); + + if (++depth > config.maxDepth) { + return printAsLeaf(name); + } + + if (val[IS_KEYED_SENTINEL]) { + return ( + name + + SPACE + + '{' + // from Immutable collection of entries or from ECMAScript object + (val._iter || val._object + ? (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer + ) + : LAZY) + + '}' + ); + } + + return ( + name + + SPACE + + '[' + + (val._iter || // from Immutable collection of values + val._array || // from ECMAScript array + val._collection || // from ECMAScript collection in immutable v4 + val._iterable // from ECMAScript collection in immutable v3 + ? (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + : LAZY) + + ']' + ); +}; + +const printImmutableValues = ( + val, + config, + indentation, + depth, + refs, + printer, + type +) => + ++depth > config.maxDepth + ? printAsLeaf(getImmutableName(type)) + : getImmutableName(type) + + SPACE + + '[' + + (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + + ']'; + +const serialize = (val, config, indentation, depth, refs, printer) => { + if (val[IS_MAP_SENTINEL]) { + return printImmutableEntries( + val, + config, + indentation, + depth, + refs, + printer, + val[IS_ORDERED_SENTINEL] ? 'OrderedMap' : 'Map' + ); + } + + if (val[IS_LIST_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + 'List' + ); + } + + if (val[IS_SET_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + val[IS_ORDERED_SENTINEL] ? 'OrderedSet' : 'Set' + ); + } + + if (val[IS_STACK_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + 'Stack' + ); + } + + if (val[IS_SEQ_SENTINEL]) { + return printImmutableSeq(val, config, indentation, depth, refs, printer); + } // For compatibility with immutable v3 and v4, let record be the default. + + return printImmutableRecord(val, config, indentation, depth, refs, printer); +}; // Explicitly comparing sentinel properties to true avoids false positive +// when mock identity-obj-proxy returns the key as the value for any key. + +exports.serialize = serialize; + +const test = val => + val && + (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); + +exports.test = test; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/node_modules/pretty-format/build/plugins/ReactElement.d.ts b/node_modules/pretty-format/build/plugins/ReactElement.d.ts new file mode 100644 index 0000000..fd2531b --- /dev/null +++ b/node_modules/pretty-format/build/plugins/ReactElement.d.ts @@ -0,0 +1,11 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type { NewPlugin } from '../types'; +export declare const serialize: NewPlugin['serialize']; +export declare const test: NewPlugin['test']; +declare const plugin: NewPlugin; +export default plugin; diff --git a/node_modules/pretty-format/build/plugins/ReactElement.js b/node_modules/pretty-format/build/plugins/ReactElement.js new file mode 100644 index 0000000..f45a6e0 --- /dev/null +++ b/node_modules/pretty-format/build/plugins/ReactElement.js @@ -0,0 +1,166 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; + +var ReactIs = _interopRequireWildcard(require('react-is')); + +var _markup = require('./lib/markup'); + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// Given element.props.children, or subtree during recursive traversal, +// return flattened array of children. +const getChildren = (arg, children = []) => { + if (Array.isArray(arg)) { + arg.forEach(item => { + getChildren(item, children); + }); + } else if (arg != null && arg !== false) { + children.push(arg); + } + + return children; +}; + +const getType = element => { + const type = element.type; + + if (typeof type === 'string') { + return type; + } + + if (typeof type === 'function') { + return type.displayName || type.name || 'Unknown'; + } + + if (ReactIs.isFragment(element)) { + return 'React.Fragment'; + } + + if (ReactIs.isSuspense(element)) { + return 'React.Suspense'; + } + + if (typeof type === 'object' && type !== null) { + if (ReactIs.isContextProvider(element)) { + return 'Context.Provider'; + } + + if (ReactIs.isContextConsumer(element)) { + return 'Context.Consumer'; + } + + if (ReactIs.isForwardRef(element)) { + if (type.displayName) { + return type.displayName; + } + + const functionName = type.render.displayName || type.render.name || ''; + return functionName !== '' + ? 'ForwardRef(' + functionName + ')' + : 'ForwardRef'; + } + + if (ReactIs.isMemo(element)) { + const functionName = + type.displayName || type.type.displayName || type.type.name || ''; + return functionName !== '' ? 'Memo(' + functionName + ')' : 'Memo'; + } + } + + return 'UNDEFINED'; +}; + +const getPropKeys = element => { + const {props} = element; + return Object.keys(props) + .filter(key => key !== 'children' && props[key] !== undefined) + .sort(); +}; + +const serialize = (element, config, indentation, depth, refs, printer) => + ++depth > config.maxDepth + ? (0, _markup.printElementAsLeaf)(getType(element), config) + : (0, _markup.printElement)( + getType(element), + (0, _markup.printProps)( + getPropKeys(element), + element.props, + config, + indentation + config.indent, + depth, + refs, + printer + ), + (0, _markup.printChildren)( + getChildren(element.props.children), + config, + indentation + config.indent, + depth, + refs, + printer + ), + config, + indentation + ); + +exports.serialize = serialize; + +const test = val => val != null && ReactIs.isElement(val); + +exports.test = test; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/node_modules/pretty-format/build/plugins/ReactTestComponent.d.ts b/node_modules/pretty-format/build/plugins/ReactTestComponent.d.ts new file mode 100644 index 0000000..91542d9 --- /dev/null +++ b/node_modules/pretty-format/build/plugins/ReactTestComponent.d.ts @@ -0,0 +1,18 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type { NewPlugin } from '../types'; +export declare type ReactTestObject = { + $$typeof: symbol; + type: string; + props?: Record; + children?: null | Array; +}; +declare type ReactTestChild = ReactTestObject | string | number; +export declare const serialize: NewPlugin['serialize']; +export declare const test: NewPlugin['test']; +declare const plugin: NewPlugin; +export default plugin; diff --git a/node_modules/pretty-format/build/plugins/ReactTestComponent.js b/node_modules/pretty-format/build/plugins/ReactTestComponent.js new file mode 100644 index 0000000..6e09edc --- /dev/null +++ b/node_modules/pretty-format/build/plugins/ReactTestComponent.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; + +var _markup = require('./lib/markup'); + +var global = (function () { + if (typeof globalThis !== 'undefined') { + return globalThis; + } else if (typeof global !== 'undefined') { + return global; + } else if (typeof self !== 'undefined') { + return self; + } else if (typeof window !== 'undefined') { + return window; + } else { + return Function('return this')(); + } +})(); + +var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol; +const testSymbol = + typeof Symbol === 'function' && Symbol.for + ? Symbol.for('react.test.json') + : 0xea71357; + +const getPropKeys = object => { + const {props} = object; + return props + ? Object.keys(props) + .filter(key => props[key] !== undefined) + .sort() + : []; +}; + +const serialize = (object, config, indentation, depth, refs, printer) => + ++depth > config.maxDepth + ? (0, _markup.printElementAsLeaf)(object.type, config) + : (0, _markup.printElement)( + object.type, + object.props + ? (0, _markup.printProps)( + getPropKeys(object), + object.props, + config, + indentation + config.indent, + depth, + refs, + printer + ) + : '', + object.children + ? (0, _markup.printChildren)( + object.children, + config, + indentation + config.indent, + depth, + refs, + printer + ) + : '', + config, + indentation + ); + +exports.serialize = serialize; + +const test = val => val && val.$$typeof === testSymbol; + +exports.test = test; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/node_modules/pretty-format/build/plugins/lib/escapeHTML.d.ts b/node_modules/pretty-format/build/plugins/lib/escapeHTML.d.ts new file mode 100644 index 0000000..aee0d3d --- /dev/null +++ b/node_modules/pretty-format/build/plugins/lib/escapeHTML.d.ts @@ -0,0 +1,7 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export default function escapeHTML(str: string): string; diff --git a/node_modules/pretty-format/build/plugins/lib/escapeHTML.js b/node_modules/pretty-format/build/plugins/lib/escapeHTML.js new file mode 100644 index 0000000..50dda25 --- /dev/null +++ b/node_modules/pretty-format/build/plugins/lib/escapeHTML.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = escapeHTML; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function escapeHTML(str) { + return str.replace(//g, '>'); +} diff --git a/node_modules/pretty-format/build/plugins/lib/markup.d.ts b/node_modules/pretty-format/build/plugins/lib/markup.d.ts new file mode 100644 index 0000000..60d99ab --- /dev/null +++ b/node_modules/pretty-format/build/plugins/lib/markup.d.ts @@ -0,0 +1,13 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type { Config, Printer, Refs } from '../../types'; +export declare const printProps: (keys: Array, props: Record, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string; +export declare const printChildren: (children: Array, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string; +export declare const printText: (text: string, config: Config) => string; +export declare const printComment: (comment: string, config: Config) => string; +export declare const printElement: (type: string, printedProps: string, printedChildren: string, config: Config, indentation: string) => string; +export declare const printElementAsLeaf: (type: string, config: Config) => string; diff --git a/node_modules/pretty-format/build/plugins/lib/markup.js b/node_modules/pretty-format/build/plugins/lib/markup.js new file mode 100644 index 0000000..4f677ac --- /dev/null +++ b/node_modules/pretty-format/build/plugins/lib/markup.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printText = + exports.printProps = + exports.printElementAsLeaf = + exports.printElement = + exports.printComment = + exports.printChildren = + void 0; + +var _escapeHTML = _interopRequireDefault(require('./escapeHTML')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// Return empty string if keys is empty. +const printProps = (keys, props, config, indentation, depth, refs, printer) => { + const indentationNext = indentation + config.indent; + const colors = config.colors; + return keys + .map(key => { + const value = props[key]; + let printed = printer(value, config, indentationNext, depth, refs); + + if (typeof value !== 'string') { + if (printed.indexOf('\n') !== -1) { + printed = + config.spacingOuter + + indentationNext + + printed + + config.spacingOuter + + indentation; + } + + printed = '{' + printed + '}'; + } + + return ( + config.spacingInner + + indentation + + colors.prop.open + + key + + colors.prop.close + + '=' + + colors.value.open + + printed + + colors.value.close + ); + }) + .join(''); +}; // Return empty string if children is empty. + +exports.printProps = printProps; + +const printChildren = (children, config, indentation, depth, refs, printer) => + children + .map( + child => + config.spacingOuter + + indentation + + (typeof child === 'string' + ? printText(child, config) + : printer(child, config, indentation, depth, refs)) + ) + .join(''); + +exports.printChildren = printChildren; + +const printText = (text, config) => { + const contentColor = config.colors.content; + return ( + contentColor.open + (0, _escapeHTML.default)(text) + contentColor.close + ); +}; + +exports.printText = printText; + +const printComment = (comment, config) => { + const commentColor = config.colors.comment; + return ( + commentColor.open + + '' + + commentColor.close + ); +}; // Separate the functions to format props, children, and element, +// so a plugin could override a particular function, if needed. +// Too bad, so sad: the traditional (but unnecessary) space +// in a self-closing tagColor requires a second test of printedProps. + +exports.printComment = printComment; + +const printElement = ( + type, + printedProps, + printedChildren, + config, + indentation +) => { + const tagColor = config.colors.tag; + return ( + tagColor.open + + '<' + + type + + (printedProps && + tagColor.close + + printedProps + + config.spacingOuter + + indentation + + tagColor.open) + + (printedChildren + ? '>' + + tagColor.close + + printedChildren + + config.spacingOuter + + indentation + + tagColor.open + + '' + + tagColor.close + ); +}; + +exports.printElement = printElement; + +const printElementAsLeaf = (type, config) => { + const tagColor = config.colors.tag; + return ( + tagColor.open + + '<' + + type + + tagColor.close + + ' …' + + tagColor.open + + ' />' + + tagColor.close + ); +}; + +exports.printElementAsLeaf = printElementAsLeaf; diff --git a/node_modules/pretty-format/build/types.d.ts b/node_modules/pretty-format/build/types.d.ts new file mode 100644 index 0000000..f070ad8 --- /dev/null +++ b/node_modules/pretty-format/build/types.d.ts @@ -0,0 +1,108 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare type Colors = { + comment: { + close: string; + open: string; + }; + content: { + close: string; + open: string; + }; + prop: { + close: string; + open: string; + }; + tag: { + close: string; + open: string; + }; + value: { + close: string; + open: string; + }; +}; +declare type Indent = (arg0: string) => string; +export declare type Refs = Array; +declare type Print = (arg0: unknown) => string; +export declare type Theme = { + comment: string; + content: string; + prop: string; + tag: string; + value: string; +}; +declare type ThemeReceived = { + comment?: string; + content?: string; + prop?: string; + tag?: string; + value?: string; +}; +export declare type CompareKeys = ((a: string, b: string) => number) | undefined; +export declare type Options = { + callToJSON: boolean; + compareKeys: CompareKeys; + escapeRegex: boolean; + escapeString: boolean; + highlight: boolean; + indent: number; + maxDepth: number; + min: boolean; + plugins: Plugins; + printBasicPrototype: boolean; + printFunctionName: boolean; + theme: Theme; +}; +export interface PrettyFormatOptions { + callToJSON?: boolean; + compareKeys?: CompareKeys; + escapeRegex?: boolean; + escapeString?: boolean; + highlight?: boolean; + indent?: number; + maxDepth?: number; + min?: boolean; + plugins?: Plugins; + printBasicPrototype?: boolean; + printFunctionName?: boolean; + theme?: ThemeReceived; +} +export declare type OptionsReceived = PrettyFormatOptions; +export declare type Config = { + callToJSON: boolean; + compareKeys: CompareKeys; + colors: Colors; + escapeRegex: boolean; + escapeString: boolean; + indent: string; + maxDepth: number; + min: boolean; + plugins: Plugins; + printBasicPrototype: boolean; + printFunctionName: boolean; + spacingInner: string; + spacingOuter: string; +}; +export declare type Printer = (val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string; +declare type Test = (arg0: any) => boolean; +export declare type NewPlugin = { + serialize: (val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string; + test: Test; +}; +declare type PluginOptions = { + edgeSpacing: string; + min: boolean; + spacing: string; +}; +export declare type OldPlugin = { + print: (val: unknown, print: Print, indent: Indent, options: PluginOptions, colors: Colors) => string; + test: Test; +}; +export declare type Plugin = NewPlugin | OldPlugin; +export declare type Plugins = Array; +export {}; diff --git a/node_modules/pretty-format/build/types.js b/node_modules/pretty-format/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/pretty-format/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/pretty-format/node_modules/ansi-styles/index.d.ts b/node_modules/pretty-format/node_modules/ansi-styles/index.d.ts new file mode 100644 index 0000000..e0170aa --- /dev/null +++ b/node_modules/pretty-format/node_modules/ansi-styles/index.d.ts @@ -0,0 +1,167 @@ +declare namespace ansiStyles { + interface CSPair { + /** + The ANSI terminal control sequence for starting this style. + */ + readonly open: string; + + /** + The ANSI terminal control sequence for ending this style. + */ + readonly close: string; + } + + interface ColorBase { + /** + The ANSI terminal control sequence for ending this color. + */ + readonly close: string; + + ansi256(code: number): string; + + ansi16m(red: number, green: number, blue: number): string; + } + + interface Modifier { + /** + Resets the current color chain. + */ + readonly reset: CSPair; + + /** + Make text bold. + */ + readonly bold: CSPair; + + /** + Emitting only a small amount of light. + */ + readonly dim: CSPair; + + /** + Make text italic. (Not widely supported) + */ + readonly italic: CSPair; + + /** + Make text underline. (Not widely supported) + */ + readonly underline: CSPair; + + /** + Make text overline. + + Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash. + */ + readonly overline: CSPair; + + /** + Inverse background and foreground colors. + */ + readonly inverse: CSPair; + + /** + Prints the text, but makes it invisible. + */ + readonly hidden: CSPair; + + /** + Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: CSPair; + } + + interface ForegroundColor { + readonly black: CSPair; + readonly red: CSPair; + readonly green: CSPair; + readonly yellow: CSPair; + readonly blue: CSPair; + readonly cyan: CSPair; + readonly magenta: CSPair; + readonly white: CSPair; + + /** + Alias for `blackBright`. + */ + readonly gray: CSPair; + + /** + Alias for `blackBright`. + */ + readonly grey: CSPair; + + readonly blackBright: CSPair; + readonly redBright: CSPair; + readonly greenBright: CSPair; + readonly yellowBright: CSPair; + readonly blueBright: CSPair; + readonly cyanBright: CSPair; + readonly magentaBright: CSPair; + readonly whiteBright: CSPair; + } + + interface BackgroundColor { + readonly bgBlack: CSPair; + readonly bgRed: CSPair; + readonly bgGreen: CSPair; + readonly bgYellow: CSPair; + readonly bgBlue: CSPair; + readonly bgCyan: CSPair; + readonly bgMagenta: CSPair; + readonly bgWhite: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGray: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGrey: CSPair; + + readonly bgBlackBright: CSPair; + readonly bgRedBright: CSPair; + readonly bgGreenBright: CSPair; + readonly bgYellowBright: CSPair; + readonly bgBlueBright: CSPair; + readonly bgCyanBright: CSPair; + readonly bgMagentaBright: CSPair; + readonly bgWhiteBright: CSPair; + } + + interface ConvertColor { + /** + Convert from the RGB color space to the ANSI 256 color space. + + @param red - (`0...255`) + @param green - (`0...255`) + @param blue - (`0...255`) + */ + rgbToAnsi256(red: number, green: number, blue: number): number; + + /** + Convert from the RGB HEX color space to the RGB color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToRgb(hex: string): [red: number, green: number, blue: number]; + + /** + Convert from the RGB HEX color space to the ANSI 256 color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToAnsi256(hex: string): number; + } +} + +declare const ansiStyles: { + readonly modifier: ansiStyles.Modifier; + readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase; + readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase; + readonly codes: ReadonlyMap; +} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier & ansiStyles.ConvertColor; + +export = ansiStyles; diff --git a/node_modules/pretty-format/node_modules/ansi-styles/index.js b/node_modules/pretty-format/node_modules/ansi-styles/index.js new file mode 100644 index 0000000..a9eac58 --- /dev/null +++ b/node_modules/pretty-format/node_modules/ansi-styles/index.js @@ -0,0 +1,164 @@ +'use strict'; + +const ANSI_BACKGROUND_OFFSET = 10; + +const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; + +const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi256 = wrapAnsi256(); + styles.color.ansi16m = wrapAnsi16m(); + styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + + // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js + Object.defineProperties(styles, { + rgbToAnsi256: { + value: (red, green, blue) => { + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + + if (red > 248) { + return 231; + } + + return Math.round(((red - 8) / 247) * 24) + 232; + } + + return 16 + + (36 * Math.round(red / 255 * 5)) + + (6 * Math.round(green / 255 * 5)) + + Math.round(blue / 255 * 5); + }, + enumerable: false + }, + hexToRgb: { + value: hex => { + const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + + let {colorString} = matches.groups; + + if (colorString.length === 3) { + colorString = colorString.split('').map(character => character + character).join(''); + } + + const integer = Number.parseInt(colorString, 16); + + return [ + (integer >> 16) & 0xFF, + (integer >> 8) & 0xFF, + integer & 0xFF + ]; + }, + enumerable: false + }, + hexToAnsi256: { + value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), + enumerable: false + } + }); + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); diff --git a/node_modules/pretty-format/node_modules/ansi-styles/license b/node_modules/pretty-format/node_modules/ansi-styles/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/pretty-format/node_modules/ansi-styles/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/pretty-format/node_modules/ansi-styles/package.json b/node_modules/pretty-format/node_modules/ansi-styles/package.json new file mode 100644 index 0000000..b3c89c9 --- /dev/null +++ b/node_modules/pretty-format/node_modules/ansi-styles/package.json @@ -0,0 +1,52 @@ +{ + "name": "ansi-styles", + "version": "5.2.0", + "description": "ANSI escape codes for styling strings in the terminal", + "license": "MIT", + "repository": "chalk/ansi-styles", + "funding": "https://github.com/chalk/ansi-styles?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd", + "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "devDependencies": { + "ava": "^2.4.0", + "svg-term-cli": "^2.1.1", + "tsd": "^0.14.0", + "xo": "^0.37.1" + } +} diff --git a/node_modules/pretty-format/node_modules/ansi-styles/readme.md b/node_modules/pretty-format/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000..7d12466 --- /dev/null +++ b/node_modules/pretty-format/node_modules/ansi-styles/readme.md @@ -0,0 +1,144 @@ +# ansi-styles + +> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. + + + +## Install + +``` +$ npm install ansi-styles +``` + +## Usage + +```js +const style = require('ansi-styles'); + +console.log(`${style.green.open}Hello world!${style.green.close}`); + + +// Color conversion between 256/truecolor +// NOTE: When converting from truecolor to 256 colors, the original color +// may be degraded to fit the new color palette. This means terminals +// that do not support 16 million colors will best-match the +// original color. +console.log(`${style.color.ansi256(style.rgbToAnsi256(199, 20, 250))}Hello World${style.color.close}`) +console.log(`${style.color.ansi16m(...style.hexToRgb('#abcdef'))}Hello World${style.color.close}`) +``` + +## API + +Each style has an `open` and `close` property. + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(Not widely supported)* +- `underline` +- `overline` *Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash.* +- `inverse` +- `hidden` +- `strikethrough` *(Not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `blackBright` (alias: `gray`, `grey`) +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` (alias: `bgGray`, `bgGrey`) +- `bgRedBright` +- `bgGreenBright` +- `bgYellowBright` +- `bgBlueBright` +- `bgMagentaBright` +- `bgCyanBright` +- `bgWhiteBright` + +## Advanced usage + +By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `style.modifier` +- `style.color` +- `style.bgColor` + +###### Example + +```js +console.log(style.color.green.open); +``` + +Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. + +###### Example + +```js +console.log(style.codes.get(36)); +//=> 39 +``` + +## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) + +`ansi-styles` allows converting between various color formats and ANSI escapes, with support for 256 and 16 million colors. + +The following color spaces from `color-convert` are supported: + +- `rgb` +- `hex` +- `ansi256` + +To use these, call the associated conversion function with the intended output, for example: + +```js +style.color.ansi256(style.rgbToAnsi256(100, 200, 15)); // RGB to 256 color ansi foreground code +style.bgColor.ansi256(style.hexToAnsi256('#C0FFEE')); // HEX to 256 color ansi foreground code + +style.color.ansi16m(100, 200, 15); // RGB to 16 million color foreground code +style.bgColor.ansi16m(...style.hexToRgb('#C0FFEE')); // Hex (RGB) to 16 million color foreground code +``` + +## Related + +- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + +## For enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of `ansi-styles` 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-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/pretty-format/package.json b/node_modules/pretty-format/package.json new file mode 100644 index 0000000..a8cc469 --- /dev/null +++ b/node_modules/pretty-format/package.json @@ -0,0 +1,44 @@ +{ + "name": "pretty-format", + "version": "27.5.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/pretty-format" + }, + "license": "MIT", + "description": "Stringify any JavaScript value.", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json", + "./ConvertAnsi": "./build/plugins/ConvertAnsi.js" + }, + "author": "James Kyle ", + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "devDependencies": { + "@types/react": "*", + "@types/react-is": "^17.0.0", + "@types/react-test-renderer": "*", + "immutable": "^4.0.0", + "jest-util": "^27.5.1", + "react": "*", + "react-dom": "*", + "react-test-renderer": "*" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "67c1aa20c5fec31366d733e901fee2b981cb1850" +} diff --git a/node_modules/prompts/dist/dateparts/datepart.js b/node_modules/prompts/dist/dateparts/datepart.js new file mode 100644 index 0000000..b954c5e --- /dev/null +++ b/node_modules/prompts/dist/dateparts/datepart.js @@ -0,0 +1,39 @@ +'use strict'; + +class DatePart { + constructor({ + token, + date, + parts, + locales + }) { + this.token = token; + this.date = date || new Date(); + this.parts = parts || [this]; + this.locales = locales || {}; + } + + up() {} + + down() {} + + next() { + const currentIdx = this.parts.indexOf(this); + return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + setTo(val) {} + + prev() { + let parts = [].concat(this.parts).reverse(); + const currentIdx = parts.indexOf(this); + return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + toString() { + return String(this.date); + } + +} + +module.exports = DatePart; \ No newline at end of file diff --git a/node_modules/prompts/dist/dateparts/day.js b/node_modules/prompts/dist/dateparts/day.js new file mode 100644 index 0000000..a525e92 --- /dev/null +++ b/node_modules/prompts/dist/dateparts/day.js @@ -0,0 +1,35 @@ +'use strict'; + +const DatePart = require('./datepart'); + +const pos = n => { + n = n % 10; + return n === 1 ? 'st' : n === 2 ? 'nd' : n === 3 ? 'rd' : 'th'; +}; + +class Day extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setDate(this.date.getDate() + 1); + } + + down() { + this.date.setDate(this.date.getDate() - 1); + } + + setTo(val) { + this.date.setDate(parseInt(val.substr(-2))); + } + + toString() { + let date = this.date.getDate(); + let day = this.date.getDay(); + return this.token === 'DD' ? String(date).padStart(2, '0') : this.token === 'Do' ? date + pos(date) : this.token === 'd' ? day + 1 : this.token === 'ddd' ? this.locales.weekdaysShort[day] : this.token === 'dddd' ? this.locales.weekdays[day] : date; + } + +} + +module.exports = Day; \ No newline at end of file diff --git a/node_modules/prompts/dist/dateparts/hours.js b/node_modules/prompts/dist/dateparts/hours.js new file mode 100644 index 0000000..7743632 --- /dev/null +++ b/node_modules/prompts/dist/dateparts/hours.js @@ -0,0 +1,30 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Hours extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setHours(this.date.getHours() + 1); + } + + down() { + this.date.setHours(this.date.getHours() - 1); + } + + setTo(val) { + this.date.setHours(parseInt(val.substr(-2))); + } + + toString() { + let hours = this.date.getHours(); + if (/h/.test(this.token)) hours = hours % 12 || 12; + return this.token.length > 1 ? String(hours).padStart(2, '0') : hours; + } + +} + +module.exports = Hours; \ No newline at end of file diff --git a/node_modules/prompts/dist/dateparts/index.js b/node_modules/prompts/dist/dateparts/index.js new file mode 100644 index 0000000..754516e --- /dev/null +++ b/node_modules/prompts/dist/dateparts/index.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = { + DatePart: require('./datepart'), + Meridiem: require('./meridiem'), + Day: require('./day'), + Hours: require('./hours'), + Milliseconds: require('./milliseconds'), + Minutes: require('./minutes'), + Month: require('./month'), + Seconds: require('./seconds'), + Year: require('./year') +}; \ No newline at end of file diff --git a/node_modules/prompts/dist/dateparts/meridiem.js b/node_modules/prompts/dist/dateparts/meridiem.js new file mode 100644 index 0000000..5bc8dd7 --- /dev/null +++ b/node_modules/prompts/dist/dateparts/meridiem.js @@ -0,0 +1,25 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Meridiem extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setHours((this.date.getHours() + 12) % 24); + } + + down() { + this.up(); + } + + toString() { + let meridiem = this.date.getHours() > 12 ? 'pm' : 'am'; + return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem; + } + +} + +module.exports = Meridiem; \ No newline at end of file diff --git a/node_modules/prompts/dist/dateparts/milliseconds.js b/node_modules/prompts/dist/dateparts/milliseconds.js new file mode 100644 index 0000000..3440e3a --- /dev/null +++ b/node_modules/prompts/dist/dateparts/milliseconds.js @@ -0,0 +1,28 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Milliseconds extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setMilliseconds(this.date.getMilliseconds() + 1); + } + + down() { + this.date.setMilliseconds(this.date.getMilliseconds() - 1); + } + + setTo(val) { + this.date.setMilliseconds(parseInt(val.substr(-this.token.length))); + } + + toString() { + return String(this.date.getMilliseconds()).padStart(4, '0').substr(0, this.token.length); + } + +} + +module.exports = Milliseconds; \ No newline at end of file diff --git a/node_modules/prompts/dist/dateparts/minutes.js b/node_modules/prompts/dist/dateparts/minutes.js new file mode 100644 index 0000000..2b8ef1f --- /dev/null +++ b/node_modules/prompts/dist/dateparts/minutes.js @@ -0,0 +1,29 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Minutes extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setMinutes(this.date.getMinutes() + 1); + } + + down() { + this.date.setMinutes(this.date.getMinutes() - 1); + } + + setTo(val) { + this.date.setMinutes(parseInt(val.substr(-2))); + } + + toString() { + let m = this.date.getMinutes(); + return this.token.length > 1 ? String(m).padStart(2, '0') : m; + } + +} + +module.exports = Minutes; \ No newline at end of file diff --git a/node_modules/prompts/dist/dateparts/month.js b/node_modules/prompts/dist/dateparts/month.js new file mode 100644 index 0000000..f9d4e13 --- /dev/null +++ b/node_modules/prompts/dist/dateparts/month.js @@ -0,0 +1,31 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Month extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setMonth(this.date.getMonth() + 1); + } + + down() { + this.date.setMonth(this.date.getMonth() - 1); + } + + setTo(val) { + val = parseInt(val.substr(-2)) - 1; + this.date.setMonth(val < 0 ? 0 : val); + } + + toString() { + let month = this.date.getMonth(); + let tl = this.token.length; + return tl === 2 ? String(month + 1).padStart(2, '0') : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1); + } + +} + +module.exports = Month; \ No newline at end of file diff --git a/node_modules/prompts/dist/dateparts/seconds.js b/node_modules/prompts/dist/dateparts/seconds.js new file mode 100644 index 0000000..e16f030 --- /dev/null +++ b/node_modules/prompts/dist/dateparts/seconds.js @@ -0,0 +1,29 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Seconds extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setSeconds(this.date.getSeconds() + 1); + } + + down() { + this.date.setSeconds(this.date.getSeconds() - 1); + } + + setTo(val) { + this.date.setSeconds(parseInt(val.substr(-2))); + } + + toString() { + let s = this.date.getSeconds(); + return this.token.length > 1 ? String(s).padStart(2, '0') : s; + } + +} + +module.exports = Seconds; \ No newline at end of file diff --git a/node_modules/prompts/dist/dateparts/year.js b/node_modules/prompts/dist/dateparts/year.js new file mode 100644 index 0000000..cd62677 --- /dev/null +++ b/node_modules/prompts/dist/dateparts/year.js @@ -0,0 +1,29 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Year extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setFullYear(this.date.getFullYear() + 1); + } + + down() { + this.date.setFullYear(this.date.getFullYear() - 1); + } + + setTo(val) { + this.date.setFullYear(val.substr(-4)); + } + + toString() { + let year = String(this.date.getFullYear()).padStart(4, '0'); + return this.token.length === 2 ? year.substr(-2) : year; + } + +} + +module.exports = Year; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/autocomplete.js b/node_modules/prompts/dist/elements/autocomplete.js new file mode 100644 index 0000000..60e41bc --- /dev/null +++ b/node_modules/prompts/dist/elements/autocomplete.js @@ -0,0 +1,285 @@ +'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); }); }; } + +const color = require('kleur'); + +const Prompt = require('./prompt'); + +const _require = require('sisteransi'), + erase = _require.erase, + cursor = _require.cursor; + +const _require2 = require('../util'), + style = _require2.style, + clear = _require2.clear, + figures = _require2.figures, + wrap = _require2.wrap, + entriesToDisplay = _require2.entriesToDisplay; + +const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]); + +const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]); + +const getIndex = (arr, valOrTitle) => { + const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle); + return index > -1 ? index : undefined; +}; +/** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of auto-complete choices objects + * @param {Function} [opts.suggest] Filter function. Defaults to sort by title + * @param {Number} [opts.limit=10] Max number of results to show + * @param {Number} [opts.cursor=0] Cursor start position + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.fallback] Fallback message - initial to default value + * @param {String} [opts.initial] Index of the default value + * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.noMatches] The no matches found label + */ + + +class AutocompletePrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.suggest = opts.suggest; + this.choices = opts.choices; + this.initial = typeof opts.initial === 'number' ? opts.initial : getIndex(opts.choices, opts.initial); + this.select = this.initial || opts.cursor || 0; + this.i18n = { + noMatches: opts.noMatches || 'no matches found' + }; + this.fallback = opts.fallback || this.initial; + this.clearFirst = opts.clearFirst || false; + this.suggestions = []; + this.input = ''; + this.limit = opts.limit || 10; + this.cursor = 0; + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.render = this.render.bind(this); + this.complete = this.complete.bind(this); + this.clear = clear('', this.out.columns); + this.complete(this.render); + this.render(); + } + + set fallback(fb) { + this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb; + } + + get fallback() { + let choice; + if (typeof this._fb === 'number') choice = this.choices[this._fb];else if (typeof this._fb === 'string') choice = { + title: this._fb + }; + return choice || this._fb || { + title: this.i18n.noMatches + }; + } + + moveSelect(i) { + this.select = i; + if (this.suggestions.length > 0) this.value = getVal(this.suggestions, i);else this.value = this.fallback.value; + this.fire(); + } + + complete(cb) { + var _this = this; + + return _asyncToGenerator(function* () { + const p = _this.completing = _this.suggest(_this.input, _this.choices); + + const suggestions = yield p; + if (_this.completing !== p) return; + _this.suggestions = suggestions.map((s, i, arr) => ({ + title: getTitle(arr, i), + value: getVal(arr, i), + description: s.description + })); + _this.completing = false; + const l = Math.max(suggestions.length - 1, 0); + + _this.moveSelect(Math.min(l, _this.select)); + + cb && cb(); + })(); + } + + reset() { + this.input = ''; + this.complete(() => { + this.moveSelect(this.initial !== void 0 ? this.initial : 0); + this.render(); + }); + this.render(); + } + + exit() { + if (this.clearFirst && this.input.length > 0) { + this.reset(); + } else { + this.done = this.exited = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + abort() { + this.done = this.aborted = true; + this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${c}${s2}`; + this.cursor = s1.length + 1; + this.complete(this.render); + this.render(); + } + + delete() { + if (this.cursor === 0) return this.bell(); + let s1 = this.input.slice(0, this.cursor - 1); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.cursor = this.cursor - 1; + this.render(); + } + + deleteForward() { + if (this.cursor * this.scale >= this.rendered.length) return this.bell(); + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor + 1); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.render(); + } + + first() { + this.moveSelect(0); + this.render(); + } + + last() { + this.moveSelect(this.suggestions.length - 1); + this.render(); + } + + up() { + if (this.select === 0) { + this.moveSelect(this.suggestions.length - 1); + } else { + this.moveSelect(this.select - 1); + } + + this.render(); + } + + down() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else { + this.moveSelect(this.select + 1); + } + + this.render(); + } + + next() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else this.moveSelect(this.select + 1); + + this.render(); + } + + nextPage() { + this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1)); + this.render(); + } + + prevPage() { + this.moveSelect(Math.max(this.select - this.limit, 0)); + this.render(); + } + + left() { + if (this.cursor <= 0) return this.bell(); + this.cursor = this.cursor - 1; + this.render(); + } + + right() { + if (this.cursor * this.scale >= this.rendered.length) return this.bell(); + this.cursor = this.cursor + 1; + this.render(); + } + + renderOption(v, hovered, isStart, isEnd) { + let desc; + let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : ' '; + let title = hovered ? color.cyan().underline(v.title) : v.title; + prefix = (hovered ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + + if (v.description) { + desc = ` - ${v.description}`; + + if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { + margin: 3, + width: this.out.columns + }); + } + } + + return prefix + ' ' + title + color.gray(desc || ''); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let _entriesToDisplay = entriesToDisplay(this.select, this.choices.length, this.limit), + startIndex = _entriesToDisplay.startIndex, + endIndex = _entriesToDisplay.endIndex; + + this.outputText = [style.symbol(this.done, this.aborted, this.exited), color.bold(this.msg), style.delimiter(this.completing), this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input)].join(' '); + + if (!this.done) { + const suggestions = this.suggestions.slice(startIndex, endIndex).map((item, i) => this.renderOption(item, this.select === i + startIndex, i === 0 && startIndex > 0, i + startIndex === endIndex - 1 && endIndex < this.choices.length)).join('\n'); + this.outputText += `\n` + (suggestions || color.gray(this.fallback.title)); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + +} + +module.exports = AutocompletePrompt; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/autocompleteMultiselect.js b/node_modules/prompts/dist/elements/autocompleteMultiselect.js new file mode 100644 index 0000000..ac4af0d --- /dev/null +++ b/node_modules/prompts/dist/elements/autocompleteMultiselect.js @@ -0,0 +1,201 @@ +'use strict'; + +const color = require('kleur'); + +const _require = require('sisteransi'), + cursor = _require.cursor; + +const MultiselectPrompt = require('./multiselect'); + +const _require2 = require('../util'), + clear = _require2.clear, + style = _require2.style, + figures = _require2.figures; +/** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + +class AutocompleteMultiselectPrompt extends MultiselectPrompt { + constructor(opts = {}) { + opts.overrideRender = true; + super(opts); + this.inputValue = ''; + this.clear = clear('', this.out.columns); + this.filteredOptions = this.value; + this.render(); + } + + last() { + this.cursor = this.filteredOptions.length - 1; + this.render(); + } + + next() { + this.cursor = (this.cursor + 1) % this.filteredOptions.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.filteredOptions.length - 1; + } else { + this.cursor--; + } + + this.render(); + } + + down() { + if (this.cursor === this.filteredOptions.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + + this.render(); + } + + left() { + this.filteredOptions[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.filteredOptions[this.cursor].selected = true; + this.render(); + } + + delete() { + if (this.inputValue.length) { + this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1); + this.updateFilteredOptions(); + } + } + + updateFilteredOptions() { + const currentHighlight = this.filteredOptions[this.cursor]; + this.filteredOptions = this.value.filter(v => { + if (this.inputValue) { + if (typeof v.title === 'string') { + if (v.title.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + + if (typeof v.value === 'string') { + if (v.value.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + + return false; + } + + return true; + }); + const newHighlightIndex = this.filteredOptions.findIndex(v => v === currentHighlight); + this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex; + this.render(); + } + + handleSpaceToggle() { + const v = this.filteredOptions[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + handleInputChange(c) { + this.inputValue = this.inputValue + c; + this.updateFilteredOptions(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else { + this.handleInputChange(c); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + + return ` +Instructions: + ${figures.arrowUp}/${figures.arrowDown}: Highlight option + ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection + [a,b,c]/delete: Filter choices + enter/return: Complete answer +`; + } + + return ''; + } + + renderCurrentInput() { + return ` +Filtered results for: ${this.inputValue ? this.inputValue : color.gray('Enter something to filter')}\n`; + } + + renderOption(cursor, v, i) { + let title; + if (v.disabled) title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title);else title = cursor === i ? color.cyan().underline(v.title) : v.title; + return (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + title; + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value.filter(e => e.selected).map(v => v.title).join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()]; + + if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); // print prompt + + let prompt = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(' '); + + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + + prompt += this.renderOptions(this.filteredOptions); + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } + +} + +module.exports = AutocompleteMultiselectPrompt; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/confirm.js b/node_modules/prompts/dist/elements/confirm.js new file mode 100644 index 0000000..6c342d2 --- /dev/null +++ b/node_modules/prompts/dist/elements/confirm.js @@ -0,0 +1,93 @@ +"use strict"; + +const color = require('kleur'); + +const Prompt = require('./prompt'); + +const _require = require('../util'), + style = _require.style, + clear = _require.clear; + +const _require2 = require('sisteransi'), + erase = _require2.erase, + cursor = _require2.cursor; +/** + * ConfirmPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial] Default value (true/false) + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.yes] The "Yes" label + * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no + * @param {String} [opts.no] The "No" label + * @param {String} [opts.noOption] The "No" option when choosing between yes/no + */ + + +class ConfirmPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.value = opts.initial; + this.initialValue = !!opts.initial; + this.yesMsg = opts.yes || 'yes'; + this.yesOption = opts.yesOption || '(Y/n)'; + this.noMsg = opts.no || 'no'; + this.noOption = opts.noOption || '(y/N)'; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.value = this.value || false; + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + if (c.toLowerCase() === 'y') { + this.value = true; + return this.submit(); + } + + if (c.toLowerCase() === 'n') { + this.value = false; + return this.submit(); + } + + return this.bell(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.done ? this.value ? this.yesMsg : this.noMsg : color.gray(this.initialValue ? this.yesOption : this.noOption)].join(' '); + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + +} + +module.exports = ConfirmPrompt; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/date.js b/node_modules/prompts/dist/elements/date.js new file mode 100644 index 0000000..0b254f8 --- /dev/null +++ b/node_modules/prompts/dist/elements/date.js @@ -0,0 +1,250 @@ +'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); }); }; } + +const color = require('kleur'); + +const Prompt = require('./prompt'); + +const _require = require('../util'), + style = _require.style, + clear = _require.clear, + figures = _require.figures; + +const _require2 = require('sisteransi'), + erase = _require2.erase, + cursor = _require2.cursor; + +const _require3 = require('../dateparts'), + DatePart = _require3.DatePart, + Meridiem = _require3.Meridiem, + Day = _require3.Day, + Hours = _require3.Hours, + Milliseconds = _require3.Milliseconds, + Minutes = _require3.Minutes, + Month = _require3.Month, + Seconds = _require3.Seconds, + Year = _require3.Year; + +const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g; +const regexGroups = { + 1: ({ + token + }) => token.replace(/\\(.)/g, '$1'), + 2: opts => new Day(opts), + // Day // TODO + 3: opts => new Month(opts), + // Month + 4: opts => new Year(opts), + // Year + 5: opts => new Meridiem(opts), + // AM/PM // TODO (special) + 6: opts => new Hours(opts), + // Hours + 7: opts => new Minutes(opts), + // Minutes + 8: opts => new Seconds(opts), + // Seconds + 9: opts => new Milliseconds(opts) // Fractional seconds + +}; +const dfltLocales = { + months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','), + monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), + weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), + weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',') +}; +/** + * DatePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Number} [opts.initial] Index of default value + * @param {String} [opts.mask] The format mask + * @param {object} [opts.locales] The date locales + * @param {String} [opts.error] The error message shown on invalid value + * @param {Function} [opts.validate] Function to validate the submitted value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + +class DatePrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.cursor = 0; + this.typed = ''; + this.locales = Object.assign(dfltLocales, opts.locales); + this._date = opts.initial || new Date(); + this.errorMsg = opts.error || 'Please Enter A Valid Value'; + + this.validator = opts.validate || (() => true); + + this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss'; + this.clear = clear('', this.out.columns); + this.render(); + } + + get value() { + return this.date; + } + + get date() { + return this._date; + } + + set date(date) { + if (date) this._date.setTime(date.getTime()); + } + + set mask(mask) { + let result; + this.parts = []; + + while (result = regex.exec(mask)) { + let match = result.shift(); + let idx = result.findIndex(gr => gr != null); + this.parts.push(idx in regexGroups ? regexGroups[idx]({ + token: result[idx] || match, + date: this.date, + parts: this.parts, + locales: this.locales + }) : result[idx] || match); + } + + let parts = this.parts.reduce((arr, i) => { + if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') arr[arr.length - 1] += i;else arr.push(i); + return arr; + }, []); + this.parts.splice(0); + this.parts.push(...parts); + this.reset(); + } + + moveCursor(n) { + this.typed = ''; + this.cursor = n; + this.fire(); + } + + reset() { + this.moveCursor(this.parts.findIndex(p => p instanceof DatePart)); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + validate() { + var _this = this; + + return _asyncToGenerator(function* () { + let valid = yield _this.validator(_this.value); + + if (typeof valid === 'string') { + _this.errorMsg = valid; + valid = false; + } + + _this.error = !valid; + })(); + } + + submit() { + var _this2 = this; + + return _asyncToGenerator(function* () { + yield _this2.validate(); + + if (_this2.error) { + _this2.color = 'red'; + + _this2.fire(); + + _this2.render(); + + return; + } + + _this2.done = true; + _this2.aborted = false; + + _this2.fire(); + + _this2.render(); + + _this2.out.write('\n'); + + _this2.close(); + })(); + } + + up() { + this.typed = ''; + this.parts[this.cursor].up(); + this.render(); + } + + down() { + this.typed = ''; + this.parts[this.cursor].down(); + this.render(); + } + + left() { + let prev = this.parts[this.cursor].prev(); + if (prev == null) return this.bell(); + this.moveCursor(this.parts.indexOf(prev)); + this.render(); + } + + right() { + let next = this.parts[this.cursor].next(); + if (next == null) return this.bell(); + this.moveCursor(this.parts.indexOf(next)); + this.render(); + } + + next() { + let next = this.parts[this.cursor].next(); + this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex(part => part instanceof DatePart)); + this.render(); + } + + _(c) { + if (/\d/.test(c)) { + this.typed += c; + this.parts[this.cursor].setTo(this.typed); + this.render(); + } + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); // Print prompt + + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), []).join('')].join(' '); // Print error + + if (this.error) { + this.outputText += this.errorMsg.split('\n').reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + +} + +module.exports = DatePrompt; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/index.js b/node_modules/prompts/dist/elements/index.js new file mode 100644 index 0000000..cf0ccc1 --- /dev/null +++ b/node_modules/prompts/dist/elements/index.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = { + TextPrompt: require('./text'), + SelectPrompt: require('./select'), + TogglePrompt: require('./toggle'), + DatePrompt: require('./date'), + NumberPrompt: require('./number'), + MultiselectPrompt: require('./multiselect'), + AutocompletePrompt: require('./autocomplete'), + AutocompleteMultiselectPrompt: require('./autocompleteMultiselect'), + ConfirmPrompt: require('./confirm') +}; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/multiselect.js b/node_modules/prompts/dist/elements/multiselect.js new file mode 100644 index 0000000..2d129ea --- /dev/null +++ b/node_modules/prompts/dist/elements/multiselect.js @@ -0,0 +1,289 @@ +'use strict'; + +const color = require('kleur'); + +const _require = require('sisteransi'), + cursor = _require.cursor; + +const Prompt = require('./prompt'); + +const _require2 = require('../util'), + clear = _require2.clear, + figures = _require2.figures, + style = _require2.style, + wrap = _require2.wrap, + entriesToDisplay = _require2.entriesToDisplay; +/** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + +class MultiselectPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.cursor = opts.cursor || 0; + this.scrollIndex = opts.cursor || 0; + this.hint = opts.hint || ''; + this.warn = opts.warn || '- This option is disabled -'; + this.minSelected = opts.min; + this.showMinError = false; + this.maxChoices = opts.max; + this.instructions = opts.instructions; + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') ch = { + title: ch, + value: idx + }; + return { + title: ch && (ch.title || ch.value || ch), + description: ch && ch.description, + value: ch && (ch.value === undefined ? idx : ch.value), + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.clear = clear('', this.out.columns); + + if (!opts.overrideRender) { + this.render(); + } + } + + reset() { + this.value.map(v => !v.selected); + this.cursor = 0; + this.fire(); + this.render(); + } + + selected() { + return this.value.filter(v => v.selected); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + const selected = this.value.filter(e => e.selected); + + if (this.minSelected && selected.length < this.minSelected) { + this.showMinError = true; + this.render(); + } else { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length - 1; + this.render(); + } + + next() { + this.cursor = (this.cursor + 1) % this.value.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.value.length - 1; + } else { + this.cursor--; + } + + this.render(); + } + + down() { + if (this.cursor === this.value.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + + this.render(); + } + + left() { + this.value[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.value[this.cursor].selected = true; + this.render(); + } + + handleSpaceToggle() { + const v = this.value[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + toggleAll() { + if (this.maxChoices !== undefined || this.value[this.cursor].disabled) { + return this.bell(); + } + + const newSelected = !this.value[this.cursor].selected; + this.value.filter(v => !v.disabled).forEach(v => v.selected = newSelected); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else if (c === 'a') { + this.toggleAll(); + } else { + return this.bell(); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + + return '\nInstructions:\n' + ` ${figures.arrowUp}/${figures.arrowDown}: Highlight option\n` + ` ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection\n` + (this.maxChoices === undefined ? ` a: Toggle all\n` : '') + ` enter/return: Complete answer`; + } + + return ''; + } + + renderOption(cursor, v, i, arrowIndicator) { + const prefix = (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' '; + let title, desc; + + if (v.disabled) { + title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + } else { + title = cursor === i ? color.cyan().underline(v.title) : v.title; + + if (cursor === i && v.description) { + desc = ` - ${v.description}`; + + if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { + margin: prefix.length, + width: this.out.columns + }); + } + } + } + + return prefix + title + color.gray(desc || ''); + } // shared with autocompleteMultiselect + + + paginateOptions(options) { + if (options.length === 0) { + return color.red('No matches for this query.'); + } + + let _entriesToDisplay = entriesToDisplay(this.cursor, options.length, this.optionsPerPage), + startIndex = _entriesToDisplay.startIndex, + endIndex = _entriesToDisplay.endIndex; + + let prefix, + styledOptions = []; + + for (let i = startIndex; i < endIndex; i++) { + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < options.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + + styledOptions.push(this.renderOption(this.cursor, options[i], i, prefix)); + } + + return '\n' + styledOptions.join('\n'); + } // shared with autocomleteMultiselect + + + renderOptions(options) { + if (!this.done) { + return this.paginateOptions(options); + } + + return ''; + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value.filter(e => e.selected).map(v => v.title).join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions()]; + + if (this.value[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); // print prompt + + let prompt = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(' '); + + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + + prompt += this.renderOptions(this.value); + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } + +} + +module.exports = MultiselectPrompt; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/number.js b/node_modules/prompts/dist/elements/number.js new file mode 100644 index 0000000..fd144af --- /dev/null +++ b/node_modules/prompts/dist/elements/number.js @@ -0,0 +1,250 @@ +"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); }); }; } + +const color = require('kleur'); + +const Prompt = require('./prompt'); + +const _require = require('sisteransi'), + cursor = _require.cursor, + erase = _require.erase; + +const _require2 = require('../util'), + style = _require2.style, + figures = _require2.figures, + clear = _require2.clear, + lines = _require2.lines; + +const isNumber = /[0-9]/; + +const isDef = any => any !== undefined; + +const round = (number, precision) => { + let factor = Math.pow(10, precision); + return Math.round(number * factor) / factor; +}; +/** + * NumberPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {Number} [opts.initial] Default value + * @param {Number} [opts.max=+Infinity] Max value + * @param {Number} [opts.min=-Infinity] Min value + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ + + +class NumberPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.transform = style.render(opts.style); + this.msg = opts.message; + this.initial = isDef(opts.initial) ? opts.initial : ''; + this.float = !!opts.float; + this.round = opts.round || 2; + this.inc = opts.increment || 1; + this.min = isDef(opts.min) ? opts.min : -Infinity; + this.max = isDef(opts.max) ? opts.max : Infinity; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + + this.validator = opts.validate || (() => true); + + this.color = `cyan`; + this.value = ``; + this.typed = ``; + this.lastHit = 0; + this.render(); + } + + set value(v) { + if (!v && v !== 0) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(`${this.initial}`)); + this._value = ``; + } else { + this.placeholder = false; + this.rendered = this.transform.render(`${round(v, this.round)}`); + this._value = round(v, this.round); + } + + this.fire(); + } + + get value() { + return this._value; + } + + parse(x) { + return this.float ? parseFloat(x) : parseInt(x); + } + + valid(c) { + return c === `-` || c === `.` && this.float || isNumber.test(c); + } + + reset() { + this.typed = ``; + this.value = ``; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + let x = this.value; + this.value = x !== `` ? x : this.initial; + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write(`\n`); + this.close(); + } + + validate() { + var _this = this; + + return _asyncToGenerator(function* () { + let valid = yield _this.validator(_this.value); + + if (typeof valid === `string`) { + _this.errorMsg = valid; + valid = false; + } + + _this.error = !valid; + })(); + } + + submit() { + var _this2 = this; + + return _asyncToGenerator(function* () { + yield _this2.validate(); + + if (_this2.error) { + _this2.color = `red`; + + _this2.fire(); + + _this2.render(); + + return; + } + + let x = _this2.value; + _this2.value = x !== `` ? x : _this2.initial; + _this2.done = true; + _this2.aborted = false; + _this2.error = false; + + _this2.fire(); + + _this2.render(); + + _this2.out.write(`\n`); + + _this2.close(); + })(); + } + + up() { + this.typed = ``; + + if (this.value === '') { + this.value = this.min - this.inc; + } + + if (this.value >= this.max) return this.bell(); + this.value += this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + down() { + this.typed = ``; + + if (this.value === '') { + this.value = this.min + this.inc; + } + + if (this.value <= this.min) return this.bell(); + this.value -= this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + delete() { + let val = this.value.toString(); + if (val.length === 0) return this.bell(); + this.value = this.parse(val = val.slice(0, -1)) || ``; + + if (this.value !== '' && this.value < this.min) { + this.value = this.min; + } + + this.color = `cyan`; + this.fire(); + this.render(); + } + + next() { + this.value = this.initial; + this.fire(); + this.render(); + } + + _(c, key) { + if (!this.valid(c)) return this.bell(); + const now = Date.now(); + if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed + + this.typed += c; + this.lastHit = now; + this.color = `cyan`; + if (c === `.`) return this.fire(); + this.value = Math.min(this.parse(this.typed), this.max); + if (this.value > this.max) this.value = this.max; + if (this.value < this.min) this.value = this.min; + this.fire(); + this.render(); + } + + render() { + if (this.closed) return; + + if (!this.firstRender) { + if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + + super.render(); + this.outputError = ''; // Print prompt + + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), !this.done || !this.done && !this.placeholder ? color[this.color]().underline(this.rendered) : this.rendered].join(` `); // Print error + + if (this.error) { + this.outputError += this.errorMsg.split(`\n`).reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore); + } + +} + +module.exports = NumberPrompt; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/prompt.js b/node_modules/prompts/dist/elements/prompt.js new file mode 100644 index 0000000..7deef04 --- /dev/null +++ b/node_modules/prompts/dist/elements/prompt.js @@ -0,0 +1,82 @@ +'use strict'; + +const readline = require('readline'); + +const _require = require('../util'), + action = _require.action; + +const EventEmitter = require('events'); + +const _require2 = require('sisteransi'), + beep = _require2.beep, + cursor = _require2.cursor; + +const color = require('kleur'); +/** + * Base prompt skeleton + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + +class Prompt extends EventEmitter { + constructor(opts = {}) { + super(); + this.firstRender = true; + this.in = opts.stdin || process.stdin; + this.out = opts.stdout || process.stdout; + + this.onRender = (opts.onRender || (() => void 0)).bind(this); + + const rl = readline.createInterface({ + input: this.in, + escapeCodeTimeout: 50 + }); + readline.emitKeypressEvents(this.in, rl); + if (this.in.isTTY) this.in.setRawMode(true); + const isSelect = ['SelectPrompt', 'MultiselectPrompt'].indexOf(this.constructor.name) > -1; + + const keypress = (str, key) => { + let a = action(key, isSelect); + + if (a === false) { + this._ && this._(str, key); + } else if (typeof this[a] === 'function') { + this[a](key); + } else { + this.bell(); + } + }; + + this.close = () => { + this.out.write(cursor.show); + this.in.removeListener('keypress', keypress); + if (this.in.isTTY) this.in.setRawMode(false); + rl.close(); + this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value); + this.closed = true; + }; + + this.in.on('keypress', keypress); + } + + fire() { + this.emit('state', { + value: this.value, + aborted: !!this.aborted, + exited: !!this.exited + }); + } + + bell() { + this.out.write(beep); + } + + render() { + this.onRender(color); + if (this.firstRender) this.firstRender = false; + } + +} + +module.exports = Prompt; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/select.js b/node_modules/prompts/dist/elements/select.js new file mode 100644 index 0000000..5e27c69 --- /dev/null +++ b/node_modules/prompts/dist/elements/select.js @@ -0,0 +1,190 @@ +'use strict'; + +const color = require('kleur'); + +const Prompt = require('./prompt'); + +const _require = require('../util'), + style = _require.style, + clear = _require.clear, + figures = _require.figures, + wrap = _require.wrap, + entriesToDisplay = _require.entriesToDisplay; + +const _require2 = require('sisteransi'), + cursor = _require2.cursor; +/** + * SelectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {Number} [opts.initial] Index of default value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + */ + + +class SelectPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.hint = opts.hint || '- Use arrow-keys. Return to submit.'; + this.warn = opts.warn || '- This option is disabled'; + this.cursor = opts.initial || 0; + this.choices = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') ch = { + title: ch, + value: idx + }; + return { + title: ch && (ch.title || ch.value || ch), + value: ch && (ch.value === undefined ? idx : ch.value), + description: ch && ch.description, + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = (this.choices[this.cursor] || {}).value; + this.clear = clear('', this.out.columns); + this.render(); + } + + moveCursor(n) { + this.cursor = n; + this.value = this.choices[n].value; + this.fire(); + } + + reset() { + this.moveCursor(0); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + if (!this.selection.disabled) { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } else this.bell(); + } + + first() { + this.moveCursor(0); + this.render(); + } + + last() { + this.moveCursor(this.choices.length - 1); + this.render(); + } + + up() { + if (this.cursor === 0) { + this.moveCursor(this.choices.length - 1); + } else { + this.moveCursor(this.cursor - 1); + } + + this.render(); + } + + down() { + if (this.cursor === this.choices.length - 1) { + this.moveCursor(0); + } else { + this.moveCursor(this.cursor + 1); + } + + this.render(); + } + + next() { + this.moveCursor((this.cursor + 1) % this.choices.length); + this.render(); + } + + _(c, key) { + if (c === ' ') return this.submit(); + } + + get selection() { + return this.choices[this.cursor]; + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let _entriesToDisplay = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage), + startIndex = _entriesToDisplay.startIndex, + endIndex = _entriesToDisplay.endIndex; // Print prompt + + + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.done ? this.selection.title : this.selection.disabled ? color.yellow(this.warn) : color.gray(this.hint)].join(' '); // Print choices + + if (!this.done) { + this.outputText += '\n'; + + for (let i = startIndex; i < endIndex; i++) { + let title, + prefix, + desc = '', + v = this.choices[i]; // Determine whether to display "more choices" indicators + + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < this.choices.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + + if (v.disabled) { + title = this.cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + prefix = (this.cursor === i ? color.bold().gray(figures.pointer) + ' ' : ' ') + prefix; + } else { + title = this.cursor === i ? color.cyan().underline(v.title) : v.title; + prefix = (this.cursor === i ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + + if (v.description && this.cursor === i) { + desc = ` - ${v.description}`; + + if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { + margin: 3, + width: this.out.columns + }); + } + } + } + + this.outputText += `${prefix} ${title}${color.gray(desc)}\n`; + } + } + + this.out.write(this.outputText); + } + +} + +module.exports = SelectPrompt; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/text.js b/node_modules/prompts/dist/elements/text.js new file mode 100644 index 0000000..c38a070 --- /dev/null +++ b/node_modules/prompts/dist/elements/text.js @@ -0,0 +1,245 @@ +"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); }); }; } + +const color = require('kleur'); + +const Prompt = require('./prompt'); + +const _require = require('sisteransi'), + erase = _require.erase, + cursor = _require.cursor; + +const _require2 = require('../util'), + style = _require2.style, + clear = _require2.clear, + lines = _require2.lines, + figures = _require2.figures; +/** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.initial] Default value + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ + + +class TextPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.msg = opts.message; + this.initial = opts.initial || ``; + + this.validator = opts.validate || (() => true); + + this.value = ``; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.clear = clear(``, this.out.columns); + this.render(); + } + + set value(v) { + if (!v && this.initial) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(this.initial)); + } else { + this.placeholder = false; + this.rendered = this.transform.render(v); + } + + this._value = v; + this.fire(); + } + + get value() { + return this._value; + } + + reset() { + this.value = ``; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.value = this.value || this.initial; + this.done = this.aborted = true; + this.error = false; + this.red = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + validate() { + var _this = this; + + return _asyncToGenerator(function* () { + let valid = yield _this.validator(_this.value); + + if (typeof valid === `string`) { + _this.errorMsg = valid; + valid = false; + } + + _this.error = !valid; + })(); + } + + submit() { + var _this2 = this; + + return _asyncToGenerator(function* () { + _this2.value = _this2.value || _this2.initial; + _this2.cursorOffset = 0; + _this2.cursor = _this2.rendered.length; + yield _this2.validate(); + + if (_this2.error) { + _this2.red = true; + + _this2.fire(); + + _this2.render(); + + return; + } + + _this2.done = true; + _this2.aborted = false; + + _this2.fire(); + + _this2.render(); + + _this2.out.write('\n'); + + _this2.close(); + })(); + } + + next() { + if (!this.placeholder) return this.bell(); + this.value = this.initial; + this.cursor = this.rendered.length; + this.fire(); + this.render(); + } + + moveCursor(n) { + if (this.placeholder) return; + this.cursor = this.cursor + n; + this.cursorOffset += n; + } + + _(c, key) { + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${c}${s2}`; + this.red = false; + this.cursor = this.placeholder ? 0 : s1.length + 1; + this.render(); + } + + delete() { + if (this.isCursorAtStart()) return this.bell(); + let s1 = this.value.slice(0, this.cursor - 1); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${s2}`; + this.red = false; + + if (this.isCursorAtStart()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + this.moveCursor(-1); + } + + this.render(); + } + + deleteForward() { + if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell(); + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor + 1); + this.value = `${s1}${s2}`; + this.red = false; + + if (this.isCursorAtEnd()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + } + + this.render(); + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length; + this.render(); + } + + left() { + if (this.cursor <= 0 || this.placeholder) return this.bell(); + this.moveCursor(-1); + this.render(); + } + + right() { + if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell(); + this.moveCursor(1); + this.render(); + } + + isCursorAtStart() { + return this.cursor === 0 || this.placeholder && this.cursor === 1; + } + + isCursorAtEnd() { + return this.cursor === this.rendered.length || this.placeholder && this.cursor === this.rendered.length + 1; + } + + render() { + if (this.closed) return; + + if (!this.firstRender) { + if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + + super.render(); + this.outputError = ''; + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.red ? color.red(this.rendered) : this.rendered].join(` `); + + if (this.error) { + this.outputError += this.errorMsg.split(`\n`).reduce((a, l, i) => a + `\n${i ? ' ' : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0)); + } + +} + +module.exports = TextPrompt; \ No newline at end of file diff --git a/node_modules/prompts/dist/elements/toggle.js b/node_modules/prompts/dist/elements/toggle.js new file mode 100644 index 0000000..d942f60 --- /dev/null +++ b/node_modules/prompts/dist/elements/toggle.js @@ -0,0 +1,124 @@ +"use strict"; + +const color = require('kleur'); + +const Prompt = require('./prompt'); + +const _require = require('../util'), + style = _require.style, + clear = _require.clear; + +const _require2 = require('sisteransi'), + cursor = _require2.cursor, + erase = _require2.erase; +/** + * TogglePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial=false] Default value + * @param {String} [opts.active='no'] Active label + * @param {String} [opts.inactive='off'] Inactive label + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + +class TogglePrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.value = !!opts.initial; + this.active = opts.active || 'on'; + this.inactive = opts.inactive || 'off'; + this.initialValue = this.value; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + deactivate() { + if (this.value === false) return this.bell(); + this.value = false; + this.render(); + } + + activate() { + if (this.value === true) return this.bell(); + this.value = true; + this.render(); + } + + delete() { + this.deactivate(); + } + + left() { + this.deactivate(); + } + + right() { + this.activate(); + } + + down() { + this.deactivate(); + } + + up() { + this.activate(); + } + + next() { + this.value = !this.value; + this.fire(); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.value = !this.value; + } else if (c === '1') { + this.value = true; + } else if (c === '0') { + this.value = false; + } else return this.bell(); + + this.render(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.value ? this.inactive : color.cyan().underline(this.inactive), color.gray('/'), this.value ? color.cyan().underline(this.active) : this.active].join(' '); + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + +} + +module.exports = TogglePrompt; \ No newline at end of file diff --git a/node_modules/prompts/dist/index.js b/node_modules/prompts/dist/index.js new file mode 100644 index 0000000..f30e9e7 --- /dev/null +++ b/node_modules/prompts/dist/index.js @@ -0,0 +1,154 @@ +'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; } + +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + +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 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 prompts = require('./prompts'); + +const passOn = ['suggest', 'format', 'onState', 'validate', 'onRender', 'type']; + +const noop = () => {}; +/** + * Prompt for a series of questions + * @param {Array|Object} questions Single question object or Array of question objects + * @param {Function} [onSubmit] Callback function called on prompt submit + * @param {Function} [onCancel] Callback function called on cancel/abort + * @returns {Object} Object with values from user input + */ + + +function prompt() { + return _prompt.apply(this, arguments); +} + +function _prompt() { + _prompt = _asyncToGenerator(function* (questions = [], { + onSubmit = noop, + onCancel = noop + } = {}) { + const answers = {}; + const override = prompt._override || {}; + questions = [].concat(questions); + let answer, question, quit, name, type, lastPrompt; + + const getFormattedAnswer = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(function* (question, answer, skipValidation = false) { + if (!skipValidation && question.validate && question.validate(answer) !== true) { + return; + } + + return question.format ? yield question.format(answer, answers) : answer; + }); + + return function getFormattedAnswer(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + + var _iterator = _createForOfIteratorHelper(questions), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + question = _step.value; + var _question = question; + name = _question.name; + type = _question.type; + + // evaluate type first and skip if type is a falsy value + if (typeof type === 'function') { + type = yield type(answer, _objectSpread({}, answers), question); + question['type'] = type; + } + + if (!type) continue; // if property is a function, invoke it unless it's a special function + + for (let key in question) { + if (passOn.includes(key)) continue; + let value = question[key]; + question[key] = typeof value === 'function' ? yield value(answer, _objectSpread({}, answers), lastPrompt) : value; + } + + lastPrompt = question; + + if (typeof question.message !== 'string') { + throw new Error('prompt message is required'); + } // update vars in case they changed + + + var _question2 = question; + name = _question2.name; + type = _question2.type; + + if (prompts[type] === void 0) { + throw new Error(`prompt type (${type}) is not defined`); + } + + if (override[question.name] !== undefined) { + answer = yield getFormattedAnswer(question, override[question.name]); + + if (answer !== undefined) { + answers[name] = answer; + continue; + } + } + + try { + // Get the injected answer if there is one or prompt the user + answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : yield prompts[type](question); + answers[name] = answer = yield getFormattedAnswer(question, answer, true); + quit = yield onSubmit(question, answer, answers); + } catch (err) { + quit = !(yield onCancel(question, answers)); + } + + if (quit) return answers; + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return answers; + }); + return _prompt.apply(this, arguments); +} + +function getInjectedAnswer(injected, deafultValue) { + const answer = injected.shift(); + + if (answer instanceof Error) { + throw answer; + } + + return answer === undefined ? deafultValue : answer; +} + +function inject(answers) { + prompt._injected = (prompt._injected || []).concat(answers); +} + +function override(answers) { + prompt._override = Object.assign({}, answers); +} + +module.exports = Object.assign(prompt, { + prompt, + prompts, + inject, + override +}); \ No newline at end of file diff --git a/node_modules/prompts/dist/prompts.js b/node_modules/prompts/dist/prompts.js new file mode 100644 index 0000000..31f2648 --- /dev/null +++ b/node_modules/prompts/dist/prompts.js @@ -0,0 +1,222 @@ +'use strict'; + +const $ = exports; + +const el = require('./elements'); + +const noop = v => v; + +function toPrompt(type, args, opts = {}) { + return new Promise((res, rej) => { + const p = new el[type](args); + const onAbort = opts.onAbort || noop; + const onSubmit = opts.onSubmit || noop; + const onExit = opts.onExit || noop; + p.on('state', args.onState || noop); + p.on('submit', x => res(onSubmit(x))); + p.on('exit', x => res(onExit(x))); + p.on('abort', x => rej(onAbort(x))); + }); +} +/** + * Text prompt + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + +$.text = args => toPrompt('TextPrompt', args); +/** + * Password prompt with masked input + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + +$.password = args => { + args.style = 'password'; + return $.text(args); +}; +/** + * Prompt where input is invisible, like sudo + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + +$.invisible = args => { + args.style = 'invisible'; + return $.text(args); +}; +/** + * Number prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + +$.number = args => toPrompt('NumberPrompt', args); +/** + * Date prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + +$.date = args => toPrompt('DatePrompt', args); +/** + * Classic yes/no prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + +$.confirm = args => toPrompt('ConfirmPrompt', args); +/** + * List prompt, split intput string by `seperator` + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {string} [args.separator] String separator + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input, in form of an `Array` + */ + + +$.list = args => { + const sep = args.separator || ','; + return toPrompt('TextPrompt', args, { + onSubmit: str => str.split(sep).map(s => s.trim()) + }); +}; +/** + * Toggle/switch prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {string} [args.active="on"] Text for `active` state + * @param {string} [args.inactive="off"] Text for `inactive` state + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + +$.toggle = args => toPrompt('TogglePrompt', args); +/** + * Interactive select prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value }, ...]` + * @param {number} [args.initial] Index of default value + * @param {String} [args.hint] Hint to display + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + +$.select = args => toPrompt('SelectPrompt', args); +/** + * Interactive multi-select / autocompleteMultiselect prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value, [selected] }, ...]` + * @param {number} [args.max] Max select + * @param {string} [args.hint] Hint to display user + * @param {Number} [args.cursor=0] Cursor start position + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + +$.multiselect = args => { + args.choices = [].concat(args.choices || []); + + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + + return toPrompt('MultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); +}; + +$.autocompleteMultiselect = args => { + args.choices = [].concat(args.choices || []); + + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + + return toPrompt('AutocompleteMultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); +}; + +const byTitle = (input, choices) => Promise.resolve(choices.filter(item => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase())); +/** + * Interactive auto-complete prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of auto-complete choices objects `[{ title, value }, ...]` + * @param {Function} [args.suggest] Function to filter results based on user input. Defaults to sort by `title` + * @param {number} [args.limit=10] Max number of results to show + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {String} [args.initial] Index of the default value + * @param {boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {String} [args.fallback] Fallback message - defaults to initial value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + +$.autocomplete = args => { + args.suggest = args.suggest || byTitle; + args.choices = [].concat(args.choices || []); + return toPrompt('AutocompletePrompt', args); +}; \ No newline at end of file diff --git a/node_modules/prompts/dist/util/action.js b/node_modules/prompts/dist/util/action.js new file mode 100644 index 0000000..c36b7db --- /dev/null +++ b/node_modules/prompts/dist/util/action.js @@ -0,0 +1,38 @@ +'use strict'; + +module.exports = (key, isSelect) => { + if (key.meta && key.name !== 'escape') return; + + if (key.ctrl) { + if (key.name === 'a') return 'first'; + if (key.name === 'c') return 'abort'; + if (key.name === 'd') return 'abort'; + if (key.name === 'e') return 'last'; + if (key.name === 'g') return 'reset'; + } + + if (isSelect) { + if (key.name === 'j') return 'down'; + if (key.name === 'k') return 'up'; + } + + if (key.name === 'return') return 'submit'; + if (key.name === 'enter') return 'submit'; // ctrl + J + + if (key.name === 'backspace') return 'delete'; + if (key.name === 'delete') return 'deleteForward'; + if (key.name === 'abort') return 'abort'; + if (key.name === 'escape') return 'exit'; + if (key.name === 'tab') return 'next'; + if (key.name === 'pagedown') return 'nextPage'; + if (key.name === 'pageup') return 'prevPage'; // TODO create home() in prompt types (e.g. TextPrompt) + + if (key.name === 'home') return 'home'; // TODO create end() in prompt types (e.g. TextPrompt) + + if (key.name === 'end') return 'end'; + if (key.name === 'up') return 'up'; + if (key.name === 'down') return 'down'; + if (key.name === 'right') return 'right'; + if (key.name === 'left') return 'left'; + return false; +}; \ No newline at end of file diff --git a/node_modules/prompts/dist/util/clear.js b/node_modules/prompts/dist/util/clear.js new file mode 100644 index 0000000..5a313be --- /dev/null +++ b/node_modules/prompts/dist/util/clear.js @@ -0,0 +1,42 @@ +'use strict'; + +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + +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; } + +const strip = require('./strip'); + +const _require = require('sisteransi'), + erase = _require.erase, + cursor = _require.cursor; + +const width = str => [...strip(str)].length; +/** + * @param {string} prompt + * @param {number} perLine + */ + + +module.exports = function (prompt, perLine) { + if (!perLine) return erase.line + cursor.to(0); + let rows = 0; + const lines = prompt.split(/\r?\n/); + + var _iterator = _createForOfIteratorHelper(lines), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + let line = _step.value; + rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return erase.lines(rows); +}; \ No newline at end of file diff --git a/node_modules/prompts/dist/util/entriesToDisplay.js b/node_modules/prompts/dist/util/entriesToDisplay.js new file mode 100644 index 0000000..fbb963a --- /dev/null +++ b/node_modules/prompts/dist/util/entriesToDisplay.js @@ -0,0 +1,21 @@ +'use strict'; +/** + * Determine what entries should be displayed on the screen, based on the + * currently selected index and the maximum visible. Used in list-based + * prompts like `select` and `multiselect`. + * + * @param {number} cursor the currently selected entry + * @param {number} total the total entries available to display + * @param {number} [maxVisible] the number of entries that can be displayed + */ + +module.exports = (cursor, total, maxVisible) => { + maxVisible = maxVisible || total; + let startIndex = Math.min(total - maxVisible, cursor - Math.floor(maxVisible / 2)); + if (startIndex < 0) startIndex = 0; + let endIndex = Math.min(startIndex + maxVisible, total); + return { + startIndex, + endIndex + }; +}; \ No newline at end of file diff --git a/node_modules/prompts/dist/util/figures.js b/node_modules/prompts/dist/util/figures.js new file mode 100644 index 0000000..036ec50 --- /dev/null +++ b/node_modules/prompts/dist/util/figures.js @@ -0,0 +1,32 @@ +'use strict'; + +const main = { + arrowUp: '↑', + arrowDown: '↓', + arrowLeft: '←', + arrowRight: '→', + radioOn: '◉', + radioOff: '◯', + tick: '✔', + cross: '✖', + ellipsis: '…', + pointerSmall: '›', + line: '─', + pointer: '❯' +}; +const win = { + arrowUp: main.arrowUp, + arrowDown: main.arrowDown, + arrowLeft: main.arrowLeft, + arrowRight: main.arrowRight, + radioOn: '(*)', + radioOff: '( )', + tick: '√', + cross: '×', + ellipsis: '...', + pointerSmall: '»', + line: '─', + pointer: '>' +}; +const figures = process.platform === 'win32' ? win : main; +module.exports = figures; \ No newline at end of file diff --git a/node_modules/prompts/dist/util/index.js b/node_modules/prompts/dist/util/index.js new file mode 100644 index 0000000..dbfe75e --- /dev/null +++ b/node_modules/prompts/dist/util/index.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = { + action: require('./action'), + clear: require('./clear'), + style: require('./style'), + strip: require('./strip'), + figures: require('./figures'), + lines: require('./lines'), + wrap: require('./wrap'), + entriesToDisplay: require('./entriesToDisplay') +}; \ No newline at end of file diff --git a/node_modules/prompts/dist/util/lines.js b/node_modules/prompts/dist/util/lines.js new file mode 100644 index 0000000..54a939a --- /dev/null +++ b/node_modules/prompts/dist/util/lines.js @@ -0,0 +1,14 @@ +'use strict'; + +const strip = require('./strip'); +/** + * @param {string} msg + * @param {number} perLine + */ + + +module.exports = function (msg, perLine) { + let lines = String(strip(msg) || '').split(/\r?\n/); + if (!perLine) return lines.length; + return lines.map(l => Math.ceil(l.length / perLine)).reduce((a, b) => a + b); +}; \ No newline at end of file diff --git a/node_modules/prompts/dist/util/strip.js b/node_modules/prompts/dist/util/strip.js new file mode 100644 index 0000000..dd289a0 --- /dev/null +++ b/node_modules/prompts/dist/util/strip.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = str => { + const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'].join('|'); + const RGX = new RegExp(pattern, 'g'); + return typeof str === 'string' ? str.replace(RGX, '') : str; +}; \ No newline at end of file diff --git a/node_modules/prompts/dist/util/style.js b/node_modules/prompts/dist/util/style.js new file mode 100644 index 0000000..ed1a49b --- /dev/null +++ b/node_modules/prompts/dist/util/style.js @@ -0,0 +1,51 @@ +'use strict'; + +const c = require('kleur'); + +const figures = require('./figures'); // rendering user input. + + +const styles = Object.freeze({ + password: { + scale: 1, + render: input => '*'.repeat(input.length) + }, + emoji: { + scale: 2, + render: input => '😃'.repeat(input.length) + }, + invisible: { + scale: 0, + render: input => '' + }, + default: { + scale: 1, + render: input => `${input}` + } +}); + +const render = type => styles[type] || styles.default; // icon to signalize a prompt. + + +const symbols = Object.freeze({ + aborted: c.red(figures.cross), + done: c.green(figures.tick), + exited: c.yellow(figures.cross), + default: c.cyan('?') +}); + +const symbol = (done, aborted, exited) => aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default; // between the question and the user's input. + + +const delimiter = completing => c.gray(completing ? figures.ellipsis : figures.pointerSmall); + +const item = (expandable, expanded) => c.gray(expandable ? expanded ? figures.pointerSmall : '+' : figures.line); + +module.exports = { + styles, + render, + symbols, + symbol, + delimiter, + item +}; \ No newline at end of file diff --git a/node_modules/prompts/dist/util/wrap.js b/node_modules/prompts/dist/util/wrap.js new file mode 100644 index 0000000..da5e67c --- /dev/null +++ b/node_modules/prompts/dist/util/wrap.js @@ -0,0 +1,16 @@ +'use strict'; +/** + * @param {string} msg The message to wrap + * @param {object} opts + * @param {number|string} [opts.margin] Left margin + * @param {number} opts.width Maximum characters per line including the margin + */ + +module.exports = (msg, opts = {}) => { + const tab = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(' ').join('') : opts.margin || ''; + const width = opts.width; + return (msg || '').split(/\r?\n/g).map(line => line.split(/\s+/g).reduce((arr, w) => { + if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width) arr[arr.length - 1] += ` ${w}`;else arr.push(`${tab}${w}`); + return arr; + }, [tab]).join('\n')).join('\n'); +}; \ No newline at end of file diff --git a/node_modules/prompts/index.js b/node_modules/prompts/index.js new file mode 100644 index 0000000..3479956 --- /dev/null +++ b/node_modules/prompts/index.js @@ -0,0 +1,14 @@ +function isNodeLT(tar) { + tar = (Array.isArray(tar) ? tar : tar.split('.')).map(Number); + let i=0, src=process.versions.node.split('.').map(Number); + for (; i < tar.length; i++) { + if (src[i] > tar[i]) return false; + if (tar[i] > src[i]) return true; + } + return false; +} + +module.exports = + isNodeLT('8.6.0') + ? require('./dist/index.js') + : require('./lib/index.js'); diff --git a/node_modules/prompts/lib/dateparts/datepart.js b/node_modules/prompts/lib/dateparts/datepart.js new file mode 100644 index 0000000..62b893b --- /dev/null +++ b/node_modules/prompts/lib/dateparts/datepart.js @@ -0,0 +1,35 @@ +'use strict'; + +class DatePart { + constructor({token, date, parts, locales}) { + this.token = token; + this.date = date || new Date(); + this.parts = parts || [this]; + this.locales = locales || {}; + } + + up() {} + + down() {} + + next() { + const currentIdx = this.parts.indexOf(this); + return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + setTo(val) {} + + prev() { + let parts = [].concat(this.parts).reverse(); + const currentIdx = parts.indexOf(this); + return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + toString() { + return String(this.date); + } +} + +module.exports = DatePart; + + diff --git a/node_modules/prompts/lib/dateparts/day.js b/node_modules/prompts/lib/dateparts/day.js new file mode 100644 index 0000000..5db84fe --- /dev/null +++ b/node_modules/prompts/lib/dateparts/day.js @@ -0,0 +1,42 @@ +'use strict'; + +const DatePart = require('./datepart'); + +const pos = n => { + n = n % 10; + return n === 1 ? 'st' + : n === 2 ? 'nd' + : n === 3 ? 'rd' + : 'th'; +} + +class Day extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setDate(this.date.getDate() + 1); + } + + down() { + this.date.setDate(this.date.getDate() - 1); + } + + setTo(val) { + this.date.setDate(parseInt(val.substr(-2))); + } + + toString() { + let date = this.date.getDate(); + let day = this.date.getDay(); + return this.token === 'DD' ? String(date).padStart(2, '0') + : this.token === 'Do' ? date + pos(date) + : this.token === 'd' ? day + 1 + : this.token === 'ddd' ? this.locales.weekdaysShort[day] + : this.token === 'dddd' ? this.locales.weekdays[day] + : date; + } +} + +module.exports = Day; diff --git a/node_modules/prompts/lib/dateparts/hours.js b/node_modules/prompts/lib/dateparts/hours.js new file mode 100644 index 0000000..171b3d2 --- /dev/null +++ b/node_modules/prompts/lib/dateparts/hours.js @@ -0,0 +1,30 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Hours extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setHours(this.date.getHours() + 1); + } + + down() { + this.date.setHours(this.date.getHours() - 1); + } + + setTo(val) { + this.date.setHours(parseInt(val.substr(-2))); + } + + toString() { + let hours = this.date.getHours(); + if (/h/.test(this.token)) + hours = (hours % 12) || 12; + return this.token.length > 1 ? String(hours).padStart(2, '0') : hours; + } +} + +module.exports = Hours; diff --git a/node_modules/prompts/lib/dateparts/index.js b/node_modules/prompts/lib/dateparts/index.js new file mode 100644 index 0000000..dc0cc95 --- /dev/null +++ b/node_modules/prompts/lib/dateparts/index.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = { + DatePart: require('./datepart'), + Meridiem: require('./meridiem'), + Day: require('./day'), + Hours: require('./hours'), + Milliseconds: require('./milliseconds'), + Minutes: require('./minutes'), + Month: require('./month'), + Seconds: require('./seconds'), + Year: require('./year'), +} diff --git a/node_modules/prompts/lib/dateparts/meridiem.js b/node_modules/prompts/lib/dateparts/meridiem.js new file mode 100644 index 0000000..8488677 --- /dev/null +++ b/node_modules/prompts/lib/dateparts/meridiem.js @@ -0,0 +1,24 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Meridiem extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setHours((this.date.getHours() + 12) % 24); + } + + down() { + this.up(); + } + + toString() { + let meridiem = this.date.getHours() > 12 ? 'pm' : 'am'; + return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem; + } +} + +module.exports = Meridiem; diff --git a/node_modules/prompts/lib/dateparts/milliseconds.js b/node_modules/prompts/lib/dateparts/milliseconds.js new file mode 100644 index 0000000..8984270 --- /dev/null +++ b/node_modules/prompts/lib/dateparts/milliseconds.js @@ -0,0 +1,28 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Milliseconds extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setMilliseconds(this.date.getMilliseconds() + 1); + } + + down() { + this.date.setMilliseconds(this.date.getMilliseconds() - 1); + } + + setTo(val) { + this.date.setMilliseconds(parseInt(val.substr(-(this.token.length)))); + } + + toString() { + return String(this.date.getMilliseconds()).padStart(4, '0') + .substr(0, this.token.length); + } +} + +module.exports = Milliseconds; diff --git a/node_modules/prompts/lib/dateparts/minutes.js b/node_modules/prompts/lib/dateparts/minutes.js new file mode 100644 index 0000000..aa1d8f7 --- /dev/null +++ b/node_modules/prompts/lib/dateparts/minutes.js @@ -0,0 +1,28 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Minutes extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setMinutes(this.date.getMinutes() + 1); + } + + down() { + this.date.setMinutes(this.date.getMinutes() - 1); + } + + setTo(val) { + this.date.setMinutes(parseInt(val.substr(-2))); + } + + toString() { + let m = this.date.getMinutes(); + return this.token.length > 1 ? String(m).padStart(2, '0') : m; + } +} + +module.exports = Minutes; diff --git a/node_modules/prompts/lib/dateparts/month.js b/node_modules/prompts/lib/dateparts/month.js new file mode 100644 index 0000000..f656455 --- /dev/null +++ b/node_modules/prompts/lib/dateparts/month.js @@ -0,0 +1,33 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Month extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setMonth(this.date.getMonth() + 1); + } + + down() { + this.date.setMonth(this.date.getMonth() - 1); + } + + setTo(val) { + val = parseInt(val.substr(-2)) - 1; + this.date.setMonth(val < 0 ? 0 : val); + } + + toString() { + let month = this.date.getMonth(); + let tl = this.token.length; + return tl === 2 ? String(month + 1).padStart(2, '0') + : tl === 3 ? this.locales.monthsShort[month] + : tl === 4 ? this.locales.months[month] + : String(month + 1); + } +} + +module.exports = Month; diff --git a/node_modules/prompts/lib/dateparts/seconds.js b/node_modules/prompts/lib/dateparts/seconds.js new file mode 100644 index 0000000..0c1a1a4 --- /dev/null +++ b/node_modules/prompts/lib/dateparts/seconds.js @@ -0,0 +1,28 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Seconds extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setSeconds(this.date.getSeconds() + 1); + } + + down() { + this.date.setSeconds(this.date.getSeconds() - 1); + } + + setTo(val) { + this.date.setSeconds(parseInt(val.substr(-2))); + } + + toString() { + let s = this.date.getSeconds(); + return this.token.length > 1 ? String(s).padStart(2, '0') : s; + } +} + +module.exports = Seconds; diff --git a/node_modules/prompts/lib/dateparts/year.js b/node_modules/prompts/lib/dateparts/year.js new file mode 100644 index 0000000..f068e43 --- /dev/null +++ b/node_modules/prompts/lib/dateparts/year.js @@ -0,0 +1,28 @@ +'use strict'; + +const DatePart = require('./datepart'); + +class Year extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setFullYear(this.date.getFullYear() + 1); + } + + down() { + this.date.setFullYear(this.date.getFullYear() - 1); + } + + setTo(val) { + this.date.setFullYear(val.substr(-4)); + } + + toString() { + let year = String(this.date.getFullYear()).padStart(4, '0'); + return this.token.length === 2 ? year.substr(-2) : year; + } +} + +module.exports = Year; diff --git a/node_modules/prompts/lib/elements/autocomplete.js b/node_modules/prompts/lib/elements/autocomplete.js new file mode 100644 index 0000000..8e06da2 --- /dev/null +++ b/node_modules/prompts/lib/elements/autocomplete.js @@ -0,0 +1,264 @@ +'use strict'; + +const color = require('kleur'); +const Prompt = require('./prompt'); +const { erase, cursor } = require('sisteransi'); +const { style, clear, figures, wrap, entriesToDisplay } = require('../util'); + +const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]); +const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]); +const getIndex = (arr, valOrTitle) => { + const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle); + return index > -1 ? index : undefined; +}; + +/** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of auto-complete choices objects + * @param {Function} [opts.suggest] Filter function. Defaults to sort by title + * @param {Number} [opts.limit=10] Max number of results to show + * @param {Number} [opts.cursor=0] Cursor start position + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.fallback] Fallback message - initial to default value + * @param {String} [opts.initial] Index of the default value + * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.noMatches] The no matches found label + */ +class AutocompletePrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.suggest = opts.suggest; + this.choices = opts.choices; + this.initial = typeof opts.initial === 'number' + ? opts.initial + : getIndex(opts.choices, opts.initial); + this.select = this.initial || opts.cursor || 0; + this.i18n = { noMatches: opts.noMatches || 'no matches found' }; + this.fallback = opts.fallback || this.initial; + this.clearFirst = opts.clearFirst || false; + this.suggestions = []; + this.input = ''; + this.limit = opts.limit || 10; + this.cursor = 0; + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.render = this.render.bind(this); + this.complete = this.complete.bind(this); + this.clear = clear('', this.out.columns); + this.complete(this.render); + this.render(); + } + + set fallback(fb) { + this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb; + } + + get fallback() { + let choice; + if (typeof this._fb === 'number') + choice = this.choices[this._fb]; + else if (typeof this._fb === 'string') + choice = { title: this._fb }; + return choice || this._fb || { title: this.i18n.noMatches }; + } + + moveSelect(i) { + this.select = i; + if (this.suggestions.length > 0) + this.value = getVal(this.suggestions, i); + else this.value = this.fallback.value; + this.fire(); + } + + async complete(cb) { + const p = (this.completing = this.suggest(this.input, this.choices)); + const suggestions = await p; + + if (this.completing !== p) return; + this.suggestions = suggestions + .map((s, i, arr) => ({ title: getTitle(arr, i), value: getVal(arr, i), description: s.description })); + this.completing = false; + const l = Math.max(suggestions.length - 1, 0); + this.moveSelect(Math.min(l, this.select)); + + cb && cb(); + } + + reset() { + this.input = ''; + this.complete(() => { + this.moveSelect(this.initial !== void 0 ? this.initial : 0); + this.render(); + }); + this.render(); + } + + exit() { + if (this.clearFirst && this.input.length > 0) { + this.reset(); + } else { + this.done = this.exited = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + abort() { + this.done = this.aborted = true; + this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${c}${s2}`; + this.cursor = s1.length+1; + this.complete(this.render); + this.render(); + } + + delete() { + if (this.cursor === 0) return this.bell(); + let s1 = this.input.slice(0, this.cursor-1); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.cursor = this.cursor-1; + this.render(); + } + + deleteForward() { + if(this.cursor*this.scale >= this.rendered.length) return this.bell(); + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor+1); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.render(); + } + + first() { + this.moveSelect(0); + this.render(); + } + + last() { + this.moveSelect(this.suggestions.length - 1); + this.render(); + } + + up() { + if (this.select === 0) { + this.moveSelect(this.suggestions.length - 1); + } else { + this.moveSelect(this.select - 1); + } + this.render(); + } + + down() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else { + this.moveSelect(this.select + 1); + } + this.render(); + } + + next() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else this.moveSelect(this.select + 1); + this.render(); + } + + nextPage() { + this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1)); + this.render(); + } + + prevPage() { + this.moveSelect(Math.max(this.select - this.limit, 0)); + this.render(); + } + + left() { + if (this.cursor <= 0) return this.bell(); + this.cursor = this.cursor-1; + this.render(); + } + + right() { + if (this.cursor*this.scale >= this.rendered.length) return this.bell(); + this.cursor = this.cursor+1; + this.render(); + } + + renderOption(v, hovered, isStart, isEnd) { + let desc; + let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : ' '; + let title = hovered ? color.cyan().underline(v.title) : v.title; + prefix = (hovered ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + if (v.description) { + desc = ` - ${v.description}`; + if (prefix.length + title.length + desc.length >= this.out.columns + || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns }) + } + } + return prefix + ' ' + title + color.gray(desc || ''); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let { startIndex, endIndex } = entriesToDisplay(this.select, this.choices.length, this.limit); + + this.outputText = [ + style.symbol(this.done, this.aborted, this.exited), + color.bold(this.msg), + style.delimiter(this.completing), + this.done && this.suggestions[this.select] + ? this.suggestions[this.select].title + : this.rendered = this.transform.render(this.input) + ].join(' '); + + if (!this.done) { + const suggestions = this.suggestions + .slice(startIndex, endIndex) + .map((item, i) => this.renderOption(item, + this.select === i + startIndex, + i === 0 && startIndex > 0, + i + startIndex === endIndex - 1 && endIndex < this.choices.length)) + .join('\n'); + this.outputText += `\n` + (suggestions || color.gray(this.fallback.title)); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } +} + +module.exports = AutocompletePrompt; diff --git a/node_modules/prompts/lib/elements/autocompleteMultiselect.js b/node_modules/prompts/lib/elements/autocompleteMultiselect.js new file mode 100644 index 0000000..b64510f --- /dev/null +++ b/node_modules/prompts/lib/elements/autocompleteMultiselect.js @@ -0,0 +1,194 @@ +'use strict'; + +const color = require('kleur'); +const { cursor } = require('sisteransi'); +const MultiselectPrompt = require('./multiselect'); +const { clear, style, figures } = require('../util'); +/** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ +class AutocompleteMultiselectPrompt extends MultiselectPrompt { + constructor(opts={}) { + opts.overrideRender = true; + super(opts); + this.inputValue = ''; + this.clear = clear('', this.out.columns); + this.filteredOptions = this.value; + this.render(); + } + + last() { + this.cursor = this.filteredOptions.length - 1; + this.render(); + } + next() { + this.cursor = (this.cursor + 1) % this.filteredOptions.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.filteredOptions.length - 1; + } else { + this.cursor--; + } + this.render(); + } + + down() { + if (this.cursor === this.filteredOptions.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + this.render(); + } + + left() { + this.filteredOptions[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.filteredOptions[this.cursor].selected = true; + this.render(); + } + + delete() { + if (this.inputValue.length) { + this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1); + this.updateFilteredOptions(); + } + } + + updateFilteredOptions() { + const currentHighlight = this.filteredOptions[this.cursor]; + this.filteredOptions = this.value + .filter(v => { + if (this.inputValue) { + if (typeof v.title === 'string') { + if (v.title.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + if (typeof v.value === 'string') { + if (v.value.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + return false; + } + return true; + }); + const newHighlightIndex = this.filteredOptions.findIndex(v => v === currentHighlight) + this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex; + this.render(); + } + + handleSpaceToggle() { + const v = this.filteredOptions[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + handleInputChange(c) { + this.inputValue = this.inputValue + c; + this.updateFilteredOptions(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else { + this.handleInputChange(c); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + return ` +Instructions: + ${figures.arrowUp}/${figures.arrowDown}: Highlight option + ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection + [a,b,c]/delete: Filter choices + enter/return: Complete answer +`; + } + return ''; + } + + renderCurrentInput() { + return ` +Filtered results for: ${this.inputValue ? this.inputValue : color.gray('Enter something to filter')}\n`; + } + + renderOption(cursor, v, i) { + let title; + if (v.disabled) title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + else title = cursor === i ? color.cyan().underline(v.title) : v.title; + return (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + title + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value + .filter(e => e.selected) + .map(v => v.title) + .join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()]; + + if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); + + // print prompt + + let prompt = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.renderDoneOrInstructions() + ].join(' '); + + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + prompt += this.renderOptions(this.filteredOptions); + + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } +} + +module.exports = AutocompleteMultiselectPrompt; diff --git a/node_modules/prompts/lib/elements/confirm.js b/node_modules/prompts/lib/elements/confirm.js new file mode 100644 index 0000000..7a9173f --- /dev/null +++ b/node_modules/prompts/lib/elements/confirm.js @@ -0,0 +1,89 @@ +const color = require('kleur'); +const Prompt = require('./prompt'); +const { style, clear } = require('../util'); +const { erase, cursor } = require('sisteransi'); + +/** + * ConfirmPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial] Default value (true/false) + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.yes] The "Yes" label + * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no + * @param {String} [opts.no] The "No" label + * @param {String} [opts.noOption] The "No" option when choosing between yes/no + */ +class ConfirmPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.value = opts.initial; + this.initialValue = !!opts.initial; + this.yesMsg = opts.yes || 'yes'; + this.yesOption = opts.yesOption || '(Y/n)'; + this.noMsg = opts.no || 'no'; + this.noOption = opts.noOption || '(y/N)'; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.value = this.value || false; + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + if (c.toLowerCase() === 'y') { + this.value = true; + return this.submit(); + } + if (c.toLowerCase() === 'n') { + this.value = false; + return this.submit(); + } + return this.bell(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + this.done ? (this.value ? this.yesMsg : this.noMsg) + : color.gray(this.initialValue ? this.yesOption : this.noOption) + ].join(' '); + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } +} + +module.exports = ConfirmPrompt; diff --git a/node_modules/prompts/lib/elements/date.js b/node_modules/prompts/lib/elements/date.js new file mode 100644 index 0000000..71ff608 --- /dev/null +++ b/node_modules/prompts/lib/elements/date.js @@ -0,0 +1,209 @@ +'use strict'; + +const color = require('kleur'); +const Prompt = require('./prompt'); +const { style, clear, figures } = require('../util'); +const { erase, cursor } = require('sisteransi'); +const { DatePart, Meridiem, Day, Hours, Milliseconds, Minutes, Month, Seconds, Year } = require('../dateparts'); + +const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g; +const regexGroups = { + 1: ({token}) => token.replace(/\\(.)/g, '$1'), + 2: (opts) => new Day(opts), // Day // TODO + 3: (opts) => new Month(opts), // Month + 4: (opts) => new Year(opts), // Year + 5: (opts) => new Meridiem(opts), // AM/PM // TODO (special) + 6: (opts) => new Hours(opts), // Hours + 7: (opts) => new Minutes(opts), // Minutes + 8: (opts) => new Seconds(opts), // Seconds + 9: (opts) => new Milliseconds(opts), // Fractional seconds +} + +const dfltLocales = { + months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','), + monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), + weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), + weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',') +} + + +/** + * DatePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Number} [opts.initial] Index of default value + * @param {String} [opts.mask] The format mask + * @param {object} [opts.locales] The date locales + * @param {String} [opts.error] The error message shown on invalid value + * @param {Function} [opts.validate] Function to validate the submitted value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ +class DatePrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.cursor = 0; + this.typed = ''; + this.locales = Object.assign(dfltLocales, opts.locales); + this._date = opts.initial || new Date(); + this.errorMsg = opts.error || 'Please Enter A Valid Value'; + this.validator = opts.validate || (() => true); + this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss'; + this.clear = clear('', this.out.columns); + this.render(); + } + + get value() { + return this.date + } + + get date() { + return this._date; + } + + set date(date) { + if (date) this._date.setTime(date.getTime()); + } + + set mask(mask) { + let result; + this.parts = []; + while(result = regex.exec(mask)) { + let match = result.shift(); + let idx = result.findIndex(gr => gr != null); + this.parts.push(idx in regexGroups + ? regexGroups[idx]({ token: result[idx] || match, date: this.date, parts: this.parts, locales: this.locales }) + : result[idx] || match); + } + + let parts = this.parts.reduce((arr, i) => { + if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') + arr[arr.length - 1] += i; + else arr.push(i); + return arr; + }, []); + + this.parts.splice(0); + this.parts.push(...parts); + this.reset(); + } + + moveCursor(n) { + this.typed = ''; + this.cursor = n; + this.fire(); + } + + reset() { + this.moveCursor(this.parts.findIndex(p => p instanceof DatePart)); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + async validate() { + let valid = await this.validator(this.value); + if (typeof valid === 'string') { + this.errorMsg = valid; + valid = false; + } + this.error = !valid; + } + + async submit() { + await this.validate(); + if (this.error) { + this.color = 'red'; + this.fire(); + this.render(); + return; + } + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + up() { + this.typed = ''; + this.parts[this.cursor].up(); + this.render(); + } + + down() { + this.typed = ''; + this.parts[this.cursor].down(); + this.render(); + } + + left() { + let prev = this.parts[this.cursor].prev(); + if (prev == null) return this.bell(); + this.moveCursor(this.parts.indexOf(prev)); + this.render(); + } + + right() { + let next = this.parts[this.cursor].next(); + if (next == null) return this.bell(); + this.moveCursor(this.parts.indexOf(next)); + this.render(); + } + + next() { + let next = this.parts[this.cursor].next(); + this.moveCursor(next + ? this.parts.indexOf(next) + : this.parts.findIndex((part) => part instanceof DatePart)); + this.render(); + } + + _(c) { + if (/\d/.test(c)) { + this.typed += c; + this.parts[this.cursor].setTo(this.typed); + this.render(); + } + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + // Print prompt + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), []) + .join('') + ].join(' '); + + // Print error + if (this.error) { + this.outputText += this.errorMsg.split('\n').reduce( + (a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } +} + +module.exports = DatePrompt; diff --git a/node_modules/prompts/lib/elements/index.js b/node_modules/prompts/lib/elements/index.js new file mode 100644 index 0000000..2556dd0 --- /dev/null +++ b/node_modules/prompts/lib/elements/index.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = { + TextPrompt: require('./text'), + SelectPrompt: require('./select'), + TogglePrompt: require('./toggle'), + DatePrompt: require('./date'), + NumberPrompt: require('./number'), + MultiselectPrompt: require('./multiselect'), + AutocompletePrompt: require('./autocomplete'), + AutocompleteMultiselectPrompt: require('./autocompleteMultiselect'), + ConfirmPrompt: require('./confirm') +}; diff --git a/node_modules/prompts/lib/elements/multiselect.js b/node_modules/prompts/lib/elements/multiselect.js new file mode 100644 index 0000000..99b393f --- /dev/null +++ b/node_modules/prompts/lib/elements/multiselect.js @@ -0,0 +1,271 @@ +'use strict'; + +const color = require('kleur'); +const { cursor } = require('sisteransi'); +const Prompt = require('./prompt'); +const { clear, figures, style, wrap, entriesToDisplay } = require('../util'); + +/** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ +class MultiselectPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.cursor = opts.cursor || 0; + this.scrollIndex = opts.cursor || 0; + this.hint = opts.hint || ''; + this.warn = opts.warn || '- This option is disabled -'; + this.minSelected = opts.min; + this.showMinError = false; + this.maxChoices = opts.max; + this.instructions = opts.instructions; + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') + ch = {title: ch, value: idx}; + return { + title: ch && (ch.title || ch.value || ch), + description: ch && ch.description, + value: ch && (ch.value === undefined ? idx : ch.value), + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.clear = clear('', this.out.columns); + if (!opts.overrideRender) { + this.render(); + } + } + + reset() { + this.value.map(v => !v.selected); + this.cursor = 0; + this.fire(); + this.render(); + } + + selected() { + return this.value.filter(v => v.selected); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + const selected = this.value + .filter(e => e.selected); + if (this.minSelected && selected.length < this.minSelected) { + this.showMinError = true; + this.render(); + } else { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length - 1; + this.render(); + } + next() { + this.cursor = (this.cursor + 1) % this.value.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.value.length - 1; + } else { + this.cursor--; + } + this.render(); + } + + down() { + if (this.cursor === this.value.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + this.render(); + } + + left() { + this.value[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.value[this.cursor].selected = true; + this.render(); + } + + handleSpaceToggle() { + const v = this.value[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + toggleAll() { + if (this.maxChoices !== undefined || this.value[this.cursor].disabled) { + return this.bell(); + } + + const newSelected = !this.value[this.cursor].selected; + this.value.filter(v => !v.disabled).forEach(v => v.selected = newSelected); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else if (c === 'a') { + this.toggleAll(); + } else { + return this.bell(); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + return '\nInstructions:\n' + + ` ${figures.arrowUp}/${figures.arrowDown}: Highlight option\n` + + ` ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection\n` + + (this.maxChoices === undefined ? ` a: Toggle all\n` : '') + + ` enter/return: Complete answer`; + } + return ''; + } + + renderOption(cursor, v, i, arrowIndicator) { + const prefix = (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' '; + let title, desc; + + if (v.disabled) { + title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + } else { + title = cursor === i ? color.cyan().underline(v.title) : v.title; + if (cursor === i && v.description) { + desc = ` - ${v.description}`; + if (prefix.length + title.length + desc.length >= this.out.columns + || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { margin: prefix.length, width: this.out.columns }); + } + } + } + + return prefix + title + color.gray(desc || ''); + } + + // shared with autocompleteMultiselect + paginateOptions(options) { + if (options.length === 0) { + return color.red('No matches for this query.'); + } + + let { startIndex, endIndex } = entriesToDisplay(this.cursor, options.length, this.optionsPerPage); + let prefix, styledOptions = []; + + for (let i = startIndex; i < endIndex; i++) { + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < options.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + styledOptions.push(this.renderOption(this.cursor, options[i], i, prefix)); + } + + return '\n' + styledOptions.join('\n'); + } + + // shared with autocomleteMultiselect + renderOptions(options) { + if (!this.done) { + return this.paginateOptions(options); + } + return ''; + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value + .filter(e => e.selected) + .map(v => v.title) + .join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions()]; + + if (this.value[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); + + // print prompt + let prompt = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.renderDoneOrInstructions() + ].join(' '); + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + prompt += this.renderOptions(this.value); + + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } +} + +module.exports = MultiselectPrompt; diff --git a/node_modules/prompts/lib/elements/number.js b/node_modules/prompts/lib/elements/number.js new file mode 100644 index 0000000..dc3efe9 --- /dev/null +++ b/node_modules/prompts/lib/elements/number.js @@ -0,0 +1,213 @@ +const color = require('kleur'); +const Prompt = require('./prompt'); +const { cursor, erase } = require('sisteransi'); +const { style, figures, clear, lines } = require('../util'); + +const isNumber = /[0-9]/; +const isDef = any => any !== undefined; +const round = (number, precision) => { + let factor = Math.pow(10, precision); + return Math.round(number * factor) / factor; +} + +/** + * NumberPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {Number} [opts.initial] Default value + * @param {Number} [opts.max=+Infinity] Max value + * @param {Number} [opts.min=-Infinity] Min value + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ +class NumberPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.transform = style.render(opts.style); + this.msg = opts.message; + this.initial = isDef(opts.initial) ? opts.initial : ''; + this.float = !!opts.float; + this.round = opts.round || 2; + this.inc = opts.increment || 1; + this.min = isDef(opts.min) ? opts.min : -Infinity; + this.max = isDef(opts.max) ? opts.max : Infinity; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + this.validator = opts.validate || (() => true); + this.color = `cyan`; + this.value = ``; + this.typed = ``; + this.lastHit = 0; + this.render(); + } + + set value(v) { + if (!v && v !== 0) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(`${this.initial}`)); + this._value = ``; + } else { + this.placeholder = false; + this.rendered = this.transform.render(`${round(v, this.round)}`); + this._value = round(v, this.round); + } + this.fire(); + } + + get value() { + return this._value; + } + + parse(x) { + return this.float ? parseFloat(x) : parseInt(x); + } + + valid(c) { + return c === `-` || c === `.` && this.float || isNumber.test(c) + } + + reset() { + this.typed = ``; + this.value = ``; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + let x = this.value; + this.value = x !== `` ? x : this.initial; + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write(`\n`); + this.close(); + } + + async validate() { + let valid = await this.validator(this.value); + if (typeof valid === `string`) { + this.errorMsg = valid; + valid = false; + } + this.error = !valid; + } + + async submit() { + await this.validate(); + if (this.error) { + this.color = `red`; + this.fire(); + this.render(); + return; + } + let x = this.value; + this.value = x !== `` ? x : this.initial; + this.done = true; + this.aborted = false; + this.error = false; + this.fire(); + this.render(); + this.out.write(`\n`); + this.close(); + } + + up() { + this.typed = ``; + if(this.value === '') { + this.value = this.min - this.inc; + } + if (this.value >= this.max) return this.bell(); + this.value += this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + down() { + this.typed = ``; + if(this.value === '') { + this.value = this.min + this.inc; + } + if (this.value <= this.min) return this.bell(); + this.value -= this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + delete() { + let val = this.value.toString(); + if (val.length === 0) return this.bell(); + this.value = this.parse((val = val.slice(0, -1))) || ``; + if (this.value !== '' && this.value < this.min) { + this.value = this.min; + } + this.color = `cyan`; + this.fire(); + this.render(); + } + + next() { + this.value = this.initial; + this.fire(); + this.render(); + } + + _(c, key) { + if (!this.valid(c)) return this.bell(); + + const now = Date.now(); + if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed + this.typed += c; + this.lastHit = now; + this.color = `cyan`; + + if (c === `.`) return this.fire(); + + this.value = Math.min(this.parse(this.typed), this.max); + if (this.value > this.max) this.value = this.max; + if (this.value < this.min) this.value = this.min; + this.fire(); + this.render(); + } + + render() { + if (this.closed) return; + if (!this.firstRender) { + if (this.outputError) + this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + super.render(); + this.outputError = ''; + + // Print prompt + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + !this.done || (!this.done && !this.placeholder) + ? color[this.color]().underline(this.rendered) : this.rendered + ].join(` `); + + // Print error + if (this.error) { + this.outputError += this.errorMsg.split(`\n`) + .reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore); + } +} + +module.exports = NumberPrompt; diff --git a/node_modules/prompts/lib/elements/prompt.js b/node_modules/prompts/lib/elements/prompt.js new file mode 100644 index 0000000..b793330 --- /dev/null +++ b/node_modules/prompts/lib/elements/prompt.js @@ -0,0 +1,68 @@ +'use strict'; + +const readline = require('readline'); +const { action } = require('../util'); +const EventEmitter = require('events'); +const { beep, cursor } = require('sisteransi'); +const color = require('kleur'); + +/** + * Base prompt skeleton + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ +class Prompt extends EventEmitter { + constructor(opts={}) { + super(); + + this.firstRender = true; + this.in = opts.stdin || process.stdin; + this.out = opts.stdout || process.stdout; + this.onRender = (opts.onRender || (() => void 0)).bind(this); + const rl = readline.createInterface({ input:this.in, escapeCodeTimeout:50 }); + readline.emitKeypressEvents(this.in, rl); + + if (this.in.isTTY) this.in.setRawMode(true); + const isSelect = [ 'SelectPrompt', 'MultiselectPrompt' ].indexOf(this.constructor.name) > -1; + const keypress = (str, key) => { + let a = action(key, isSelect); + if (a === false) { + this._ && this._(str, key); + } else if (typeof this[a] === 'function') { + this[a](key); + } else { + this.bell(); + } + }; + + this.close = () => { + this.out.write(cursor.show); + this.in.removeListener('keypress', keypress); + if (this.in.isTTY) this.in.setRawMode(false); + rl.close(); + this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value); + this.closed = true; + }; + + this.in.on('keypress', keypress); + } + + fire() { + this.emit('state', { + value: this.value, + aborted: !!this.aborted, + exited: !!this.exited + }); + } + + bell() { + this.out.write(beep); + } + + render() { + this.onRender(color); + if (this.firstRender) this.firstRender = false; + } +} + +module.exports = Prompt; diff --git a/node_modules/prompts/lib/elements/select.js b/node_modules/prompts/lib/elements/select.js new file mode 100644 index 0000000..6d6727f --- /dev/null +++ b/node_modules/prompts/lib/elements/select.js @@ -0,0 +1,175 @@ +'use strict'; + +const color = require('kleur'); +const Prompt = require('./prompt'); +const { style, clear, figures, wrap, entriesToDisplay } = require('../util'); +const { cursor } = require('sisteransi'); + +/** + * SelectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {Number} [opts.initial] Index of default value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + */ +class SelectPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.hint = opts.hint || '- Use arrow-keys. Return to submit.'; + this.warn = opts.warn || '- This option is disabled'; + this.cursor = opts.initial || 0; + this.choices = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') + ch = {title: ch, value: idx}; + return { + title: ch && (ch.title || ch.value || ch), + value: ch && (ch.value === undefined ? idx : ch.value), + description: ch && ch.description, + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = (this.choices[this.cursor] || {}).value; + this.clear = clear('', this.out.columns); + this.render(); + } + + moveCursor(n) { + this.cursor = n; + this.value = this.choices[n].value; + this.fire(); + } + + reset() { + this.moveCursor(0); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + if (!this.selection.disabled) { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } else + this.bell(); + } + + first() { + this.moveCursor(0); + this.render(); + } + + last() { + this.moveCursor(this.choices.length - 1); + this.render(); + } + + up() { + if (this.cursor === 0) { + this.moveCursor(this.choices.length - 1); + } else { + this.moveCursor(this.cursor - 1); + } + this.render(); + } + + down() { + if (this.cursor === this.choices.length - 1) { + this.moveCursor(0); + } else { + this.moveCursor(this.cursor + 1); + } + this.render(); + } + + next() { + this.moveCursor((this.cursor + 1) % this.choices.length); + this.render(); + } + + _(c, key) { + if (c === ' ') return this.submit(); + } + + get selection() { + return this.choices[this.cursor]; + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let { startIndex, endIndex } = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage); + + // Print prompt + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.done ? this.selection.title : this.selection.disabled + ? color.yellow(this.warn) : color.gray(this.hint) + ].join(' '); + + // Print choices + if (!this.done) { + this.outputText += '\n'; + for (let i = startIndex; i < endIndex; i++) { + let title, prefix, desc = '', v = this.choices[i]; + + // Determine whether to display "more choices" indicators + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < this.choices.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + + if (v.disabled) { + title = this.cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + prefix = (this.cursor === i ? color.bold().gray(figures.pointer) + ' ' : ' ') + prefix; + } else { + title = this.cursor === i ? color.cyan().underline(v.title) : v.title; + prefix = (this.cursor === i ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + if (v.description && this.cursor === i) { + desc = ` - ${v.description}`; + if (prefix.length + title.length + desc.length >= this.out.columns + || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns }); + } + } + } + + this.outputText += `${prefix} ${title}${color.gray(desc)}\n`; + } + } + + this.out.write(this.outputText); + } +} + +module.exports = SelectPrompt; diff --git a/node_modules/prompts/lib/elements/text.js b/node_modules/prompts/lib/elements/text.js new file mode 100644 index 0000000..ee78181 --- /dev/null +++ b/node_modules/prompts/lib/elements/text.js @@ -0,0 +1,208 @@ +const color = require('kleur'); +const Prompt = require('./prompt'); +const { erase, cursor } = require('sisteransi'); +const { style, clear, lines, figures } = require('../util'); + +/** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.initial] Default value + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ +class TextPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.msg = opts.message; + this.initial = opts.initial || ``; + this.validator = opts.validate || (() => true); + this.value = ``; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.clear = clear(``, this.out.columns); + this.render(); + } + + set value(v) { + if (!v && this.initial) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(this.initial)); + } else { + this.placeholder = false; + this.rendered = this.transform.render(v); + } + this._value = v; + this.fire(); + } + + get value() { + return this._value; + } + + reset() { + this.value = ``; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.value = this.value || this.initial; + this.done = this.aborted = true; + this.error = false; + this.red = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + async validate() { + let valid = await this.validator(this.value); + if (typeof valid === `string`) { + this.errorMsg = valid; + valid = false; + } + this.error = !valid; + } + + async submit() { + this.value = this.value || this.initial; + this.cursorOffset = 0; + this.cursor = this.rendered.length; + await this.validate(); + if (this.error) { + this.red = true; + this.fire(); + this.render(); + return; + } + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + next() { + if (!this.placeholder) return this.bell(); + this.value = this.initial; + this.cursor = this.rendered.length; + this.fire(); + this.render(); + } + + moveCursor(n) { + if (this.placeholder) return; + this.cursor = this.cursor+n; + this.cursorOffset += n; + } + + _(c, key) { + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${c}${s2}`; + this.red = false; + this.cursor = this.placeholder ? 0 : s1.length+1; + this.render(); + } + + delete() { + if (this.isCursorAtStart()) return this.bell(); + let s1 = this.value.slice(0, this.cursor-1); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${s2}`; + this.red = false; + if (this.isCursorAtStart()) { + this.cursorOffset = 0 + } else { + this.cursorOffset++; + this.moveCursor(-1); + } + this.render(); + } + + deleteForward() { + if(this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell(); + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor+1); + this.value = `${s1}${s2}`; + this.red = false; + if (this.isCursorAtEnd()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + } + this.render(); + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length; + this.render(); + } + + left() { + if (this.cursor <= 0 || this.placeholder) return this.bell(); + this.moveCursor(-1); + this.render(); + } + + right() { + if (this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell(); + this.moveCursor(1); + this.render(); + } + + isCursorAtStart() { + return this.cursor === 0 || (this.placeholder && this.cursor === 1); + } + + isCursorAtEnd() { + return this.cursor === this.rendered.length || (this.placeholder && this.cursor === this.rendered.length + 1) + } + + render() { + if (this.closed) return; + if (!this.firstRender) { + if (this.outputError) + this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + super.render(); + this.outputError = ''; + + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + this.red ? color.red(this.rendered) : this.rendered + ].join(` `); + + if (this.error) { + this.outputError += this.errorMsg.split(`\n`) + .reduce((a, l, i) => a + `\n${i ? ' ' : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0)); + } +} + +module.exports = TextPrompt; \ No newline at end of file diff --git a/node_modules/prompts/lib/elements/toggle.js b/node_modules/prompts/lib/elements/toggle.js new file mode 100644 index 0000000..bad612c --- /dev/null +++ b/node_modules/prompts/lib/elements/toggle.js @@ -0,0 +1,118 @@ +const color = require('kleur'); +const Prompt = require('./prompt'); +const { style, clear } = require('../util'); +const { cursor, erase } = require('sisteransi'); + +/** + * TogglePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial=false] Default value + * @param {String} [opts.active='no'] Active label + * @param {String} [opts.inactive='off'] Inactive label + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ +class TogglePrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.value = !!opts.initial; + this.active = opts.active || 'on'; + this.inactive = opts.inactive || 'off'; + this.initialValue = this.value; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + deactivate() { + if (this.value === false) return this.bell(); + this.value = false; + this.render(); + } + + activate() { + if (this.value === true) return this.bell(); + this.value = true; + this.render(); + } + + delete() { + this.deactivate(); + } + left() { + this.deactivate(); + } + right() { + this.activate(); + } + down() { + this.deactivate(); + } + up() { + this.activate(); + } + + next() { + this.value = !this.value; + this.fire(); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.value = !this.value; + } else if (c === '1') { + this.value = true; + } else if (c === '0') { + this.value = false; + } else return this.bell(); + this.render(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + this.value ? this.inactive : color.cyan().underline(this.inactive), + color.gray('/'), + this.value ? color.cyan().underline(this.active) : this.active + ].join(' '); + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } +} + +module.exports = TogglePrompt; diff --git a/node_modules/prompts/lib/index.js b/node_modules/prompts/lib/index.js new file mode 100644 index 0000000..a5374d5 --- /dev/null +++ b/node_modules/prompts/lib/index.js @@ -0,0 +1,98 @@ +'use strict'; + +const prompts = require('./prompts'); + +const passOn = ['suggest', 'format', 'onState', 'validate', 'onRender', 'type']; +const noop = () => {}; + +/** + * Prompt for a series of questions + * @param {Array|Object} questions Single question object or Array of question objects + * @param {Function} [onSubmit] Callback function called on prompt submit + * @param {Function} [onCancel] Callback function called on cancel/abort + * @returns {Object} Object with values from user input + */ +async function prompt(questions=[], { onSubmit=noop, onCancel=noop }={}) { + const answers = {}; + const override = prompt._override || {}; + questions = [].concat(questions); + let answer, question, quit, name, type, lastPrompt; + + const getFormattedAnswer = async (question, answer, skipValidation = false) => { + if (!skipValidation && question.validate && question.validate(answer) !== true) { + return; + } + return question.format ? await question.format(answer, answers) : answer + }; + + for (question of questions) { + ({ name, type } = question); + + // evaluate type first and skip if type is a falsy value + if (typeof type === 'function') { + type = await type(answer, { ...answers }, question) + question['type'] = type + } + if (!type) continue; + + // if property is a function, invoke it unless it's a special function + for (let key in question) { + if (passOn.includes(key)) continue; + let value = question[key]; + question[key] = typeof value === 'function' ? await value(answer, { ...answers }, lastPrompt) : value; + } + + lastPrompt = question; + + if (typeof question.message !== 'string') { + throw new Error('prompt message is required'); + } + + // update vars in case they changed + ({ name, type } = question); + + if (prompts[type] === void 0) { + throw new Error(`prompt type (${type}) is not defined`); + } + + if (override[question.name] !== undefined) { + answer = await getFormattedAnswer(question, override[question.name]); + if (answer !== undefined) { + answers[name] = answer; + continue; + } + } + + try { + // Get the injected answer if there is one or prompt the user + answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : await prompts[type](question); + answers[name] = answer = await getFormattedAnswer(question, answer, true); + quit = await onSubmit(question, answer, answers); + } catch (err) { + quit = !(await onCancel(question, answers)); + } + + if (quit) return answers; + } + + return answers; +} + +function getInjectedAnswer(injected, deafultValue) { + const answer = injected.shift(); + if (answer instanceof Error) { + throw answer; + } + + return (answer === undefined) ? deafultValue : answer; +} + +function inject(answers) { + prompt._injected = (prompt._injected || []).concat(answers); +} + +function override(answers) { + prompt._override = Object.assign({}, answers); +} + +module.exports = Object.assign(prompt, { prompt, prompts, inject, override }); diff --git a/node_modules/prompts/lib/prompts.js b/node_modules/prompts/lib/prompts.js new file mode 100644 index 0000000..9f62556 --- /dev/null +++ b/node_modules/prompts/lib/prompts.js @@ -0,0 +1,206 @@ +'use strict'; +const $ = exports; +const el = require('./elements'); +const noop = v => v; + +function toPrompt(type, args, opts={}) { + return new Promise((res, rej) => { + const p = new el[type](args); + const onAbort = opts.onAbort || noop; + const onSubmit = opts.onSubmit || noop; + const onExit = opts.onExit || noop; + p.on('state', args.onState || noop); + p.on('submit', x => res(onSubmit(x))); + p.on('exit', x => res(onExit(x))); + p.on('abort', x => rej(onAbort(x))); + }); +} + +/** + * Text prompt + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ +$.text = args => toPrompt('TextPrompt', args); + +/** + * Password prompt with masked input + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ +$.password = args => { + args.style = 'password'; + return $.text(args); +}; + +/** + * Prompt where input is invisible, like sudo + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ +$.invisible = args => { + args.style = 'invisible'; + return $.text(args); +}; + +/** + * Number prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ +$.number = args => toPrompt('NumberPrompt', args); + +/** + * Date prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ +$.date = args => toPrompt('DatePrompt', args); + +/** + * Classic yes/no prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ +$.confirm = args => toPrompt('ConfirmPrompt', args); + +/** + * List prompt, split intput string by `seperator` + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {string} [args.separator] String separator + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input, in form of an `Array` + */ +$.list = args => { + const sep = args.separator || ','; + return toPrompt('TextPrompt', args, { + onSubmit: str => str.split(sep).map(s => s.trim()) + }); +}; + +/** + * Toggle/switch prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {string} [args.active="on"] Text for `active` state + * @param {string} [args.inactive="off"] Text for `inactive` state + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ +$.toggle = args => toPrompt('TogglePrompt', args); + +/** + * Interactive select prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value }, ...]` + * @param {number} [args.initial] Index of default value + * @param {String} [args.hint] Hint to display + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ +$.select = args => toPrompt('SelectPrompt', args); + +/** + * Interactive multi-select / autocompleteMultiselect prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value, [selected] }, ...]` + * @param {number} [args.max] Max select + * @param {string} [args.hint] Hint to display user + * @param {Number} [args.cursor=0] Cursor start position + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ +$.multiselect = args => { + args.choices = [].concat(args.choices || []); + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + return toPrompt('MultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); +}; + +$.autocompleteMultiselect = args => { + args.choices = [].concat(args.choices || []); + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + return toPrompt('AutocompleteMultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); +}; + +const byTitle = (input, choices) => Promise.resolve( + choices.filter(item => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase()) +); + +/** + * Interactive auto-complete prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of auto-complete choices objects `[{ title, value }, ...]` + * @param {Function} [args.suggest] Function to filter results based on user input. Defaults to sort by `title` + * @param {number} [args.limit=10] Max number of results to show + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {String} [args.initial] Index of the default value + * @param {boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {String} [args.fallback] Fallback message - defaults to initial value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ +$.autocomplete = args => { + args.suggest = args.suggest || byTitle; + args.choices = [].concat(args.choices || []); + return toPrompt('AutocompletePrompt', args); +}; diff --git a/node_modules/prompts/lib/util/action.js b/node_modules/prompts/lib/util/action.js new file mode 100644 index 0000000..fefbd94 --- /dev/null +++ b/node_modules/prompts/lib/util/action.js @@ -0,0 +1,39 @@ +'use strict'; + +module.exports = (key, isSelect) => { + if (key.meta && key.name !== 'escape') return; + + if (key.ctrl) { + if (key.name === 'a') return 'first'; + if (key.name === 'c') return 'abort'; + if (key.name === 'd') return 'abort'; + if (key.name === 'e') return 'last'; + if (key.name === 'g') return 'reset'; + } + + if (isSelect) { + if (key.name === 'j') return 'down'; + if (key.name === 'k') return 'up'; + } + + if (key.name === 'return') return 'submit'; + if (key.name === 'enter') return 'submit'; // ctrl + J + if (key.name === 'backspace') return 'delete'; + if (key.name === 'delete') return 'deleteForward'; + if (key.name === 'abort') return 'abort'; + if (key.name === 'escape') return 'exit'; + if (key.name === 'tab') return 'next'; + if (key.name === 'pagedown') return 'nextPage'; + if (key.name === 'pageup') return 'prevPage'; + // TODO create home() in prompt types (e.g. TextPrompt) + if (key.name === 'home') return 'home'; + // TODO create end() in prompt types (e.g. TextPrompt) + if (key.name === 'end') return 'end'; + + if (key.name === 'up') return 'up'; + if (key.name === 'down') return 'down'; + if (key.name === 'right') return 'right'; + if (key.name === 'left') return 'left'; + + return false; +}; diff --git a/node_modules/prompts/lib/util/clear.js b/node_modules/prompts/lib/util/clear.js new file mode 100644 index 0000000..e4772d5 --- /dev/null +++ b/node_modules/prompts/lib/util/clear.js @@ -0,0 +1,22 @@ +'use strict'; + +const strip = require('./strip'); +const { erase, cursor } = require('sisteransi'); + +const width = str => [...strip(str)].length; + +/** + * @param {string} prompt + * @param {number} perLine + */ +module.exports = function(prompt, perLine) { + if (!perLine) return erase.line + cursor.to(0); + + let rows = 0; + const lines = prompt.split(/\r?\n/); + for (let line of lines) { + rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine); + } + + return erase.lines(rows); +}; diff --git a/node_modules/prompts/lib/util/entriesToDisplay.js b/node_modules/prompts/lib/util/entriesToDisplay.js new file mode 100644 index 0000000..5f6efbb --- /dev/null +++ b/node_modules/prompts/lib/util/entriesToDisplay.js @@ -0,0 +1,21 @@ +'use strict'; + +/** + * Determine what entries should be displayed on the screen, based on the + * currently selected index and the maximum visible. Used in list-based + * prompts like `select` and `multiselect`. + * + * @param {number} cursor the currently selected entry + * @param {number} total the total entries available to display + * @param {number} [maxVisible] the number of entries that can be displayed + */ +module.exports = (cursor, total, maxVisible) => { + maxVisible = maxVisible || total; + + let startIndex = Math.min(total- maxVisible, cursor - Math.floor(maxVisible / 2)); + if (startIndex < 0) startIndex = 0; + + let endIndex = Math.min(startIndex + maxVisible, total); + + return { startIndex, endIndex }; +}; diff --git a/node_modules/prompts/lib/util/figures.js b/node_modules/prompts/lib/util/figures.js new file mode 100644 index 0000000..cd31b88 --- /dev/null +++ b/node_modules/prompts/lib/util/figures.js @@ -0,0 +1,33 @@ +'use strict'; + + const main = { + arrowUp: '↑', + arrowDown: '↓', + arrowLeft: '←', + arrowRight: '→', + radioOn: '◉', + radioOff: '◯', + tick: '✔', + cross: '✖', + ellipsis: '…', + pointerSmall: '›', + line: '─', + pointer: '❯' +}; +const win = { + arrowUp: main.arrowUp, + arrowDown: main.arrowDown, + arrowLeft: main.arrowLeft, + arrowRight: main.arrowRight, + radioOn: '(*)', + radioOff: '( )', + tick: '√', + cross: '×', + ellipsis: '...', + pointerSmall: '»', + line: '─', + pointer: '>' +}; +const figures = process.platform === 'win32' ? win : main; + + module.exports = figures; diff --git a/node_modules/prompts/lib/util/index.js b/node_modules/prompts/lib/util/index.js new file mode 100644 index 0000000..f815986 --- /dev/null +++ b/node_modules/prompts/lib/util/index.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = { + action: require('./action'), + clear: require('./clear'), + style: require('./style'), + strip: require('./strip'), + figures: require('./figures'), + lines: require('./lines'), + wrap: require('./wrap'), + entriesToDisplay: require('./entriesToDisplay') +}; diff --git a/node_modules/prompts/lib/util/lines.js b/node_modules/prompts/lib/util/lines.js new file mode 100644 index 0000000..de30419 --- /dev/null +++ b/node_modules/prompts/lib/util/lines.js @@ -0,0 +1,15 @@ +'use strict'; + +const strip = require('./strip'); + +/** + * @param {string} msg + * @param {number} perLine + */ +module.exports = function (msg, perLine) { + let lines = String(strip(msg) || '').split(/\r?\n/); + + if (!perLine) return lines.length; + return lines.map(l => Math.ceil(l.length / perLine)) + .reduce((a, b) => a + b); +}; diff --git a/node_modules/prompts/lib/util/strip.js b/node_modules/prompts/lib/util/strip.js new file mode 100644 index 0000000..8ebf4cb --- /dev/null +++ b/node_modules/prompts/lib/util/strip.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = str => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' + ].join('|'); + + const RGX = new RegExp(pattern, 'g'); + return typeof str === 'string' ? str.replace(RGX, '') : str; +}; diff --git a/node_modules/prompts/lib/util/style.js b/node_modules/prompts/lib/util/style.js new file mode 100644 index 0000000..1851cc7 --- /dev/null +++ b/node_modules/prompts/lib/util/style.js @@ -0,0 +1,40 @@ +'use strict'; + +const c = require('kleur'); +const figures = require('./figures'); + +// rendering user input. +const styles = Object.freeze({ + password: { scale: 1, render: input => '*'.repeat(input.length) }, + emoji: { scale: 2, render: input => '😃'.repeat(input.length) }, + invisible: { scale: 0, render: input => '' }, + default: { scale: 1, render: input => `${input}` } +}); +const render = type => styles[type] || styles.default; + +// icon to signalize a prompt. +const symbols = Object.freeze({ + aborted: c.red(figures.cross), + done: c.green(figures.tick), + exited: c.yellow(figures.cross), + default: c.cyan('?') +}); + +const symbol = (done, aborted, exited) => + aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default; + +// between the question and the user's input. +const delimiter = completing => + c.gray(completing ? figures.ellipsis : figures.pointerSmall); + +const item = (expandable, expanded) => + c.gray(expandable ? (expanded ? figures.pointerSmall : '+') : figures.line); + +module.exports = { + styles, + render, + symbols, + symbol, + delimiter, + item +}; diff --git a/node_modules/prompts/lib/util/wrap.js b/node_modules/prompts/lib/util/wrap.js new file mode 100644 index 0000000..43b5399 --- /dev/null +++ b/node_modules/prompts/lib/util/wrap.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * @param {string} msg The message to wrap + * @param {object} opts + * @param {number|string} [opts.margin] Left margin + * @param {number} opts.width Maximum characters per line including the margin + */ +module.exports = (msg, opts = {}) => { + const tab = Number.isSafeInteger(parseInt(opts.margin)) + ? new Array(parseInt(opts.margin)).fill(' ').join('') + : (opts.margin || ''); + + const width = opts.width; + + return (msg || '').split(/\r?\n/g) + .map(line => line + .split(/\s+/g) + .reduce((arr, w) => { + if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width) + arr[arr.length - 1] += ` ${w}`; + else arr.push(`${tab}${w}`); + return arr; + }, [ tab ]) + .join('\n')) + .join('\n'); +}; diff --git a/node_modules/prompts/license b/node_modules/prompts/license new file mode 100644 index 0000000..13dc83c --- /dev/null +++ b/node_modules/prompts/license @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Terkel Gjervig Nielsen + +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/prompts/package.json b/node_modules/prompts/package.json new file mode 100644 index 0000000..f7ba84b --- /dev/null +++ b/node_modules/prompts/package.json @@ -0,0 +1,53 @@ +{ + "name": "prompts", + "version": "2.4.2", + "description": "Lightweight, beautiful and user-friendly prompts", + "license": "MIT", + "repository": "terkelg/prompts", + "main": "index.js", + "author": { + "name": "Terkel Gjervig", + "email": "terkel@terkel.com", + "url": "https://terkel.com" + }, + "files": [ + "lib", + "dist", + "index.js" + ], + "scripts": { + "start": "node lib/index.js", + "build": "babel lib -d dist", + "prepublishOnly": "npm run build", + "test": "tape test/*.js | tap-spec" + }, + "keywords": [ + "ui", + "prompts", + "cli", + "prompt", + "interface", + "command-line", + "input", + "command", + "stdin", + "menu", + "ask", + "interact" + ], + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "devDependencies": { + "@babel/cli": "^7.12.1", + "@babel/core": "^7.12.3", + "@babel/plugin-proposal-object-rest-spread": "^7.12.1", + "@babel/preset-env": "^7.12.1", + "tap-spec": "^2.2.2", + "tape": "^4.13.3" + }, + "engines": { + "node": ">= 6" + } +} diff --git a/node_modules/prompts/readme.md b/node_modules/prompts/readme.md new file mode 100755 index 0000000..4a8b065 --- /dev/null +++ b/node_modules/prompts/readme.md @@ -0,0 +1,882 @@ +

+ Prompts +

+ +

❯ Prompts

+ +

+ + version + + + travis + + + downloads + + +

+ +

+ Lightweight, beautiful and user-friendly interactive prompts
+ >_ Easy to use CLI prompts to enquire users for information▌ +

+ +
+ +* **Simple**: prompts has [no big dependencies](http://npm.anvaka.com/#/view/2d/prompts) nor is it broken into a [dozen](http://npm.anvaka.com/#/view/2d/inquirer) tiny modules that only work well together. +* **User friendly**: prompt uses layout and colors to create beautiful cli interfaces. +* **Promised**: uses promises and `async`/`await`. No callback hell. +* **Flexible**: all prompts are independent and can be used on their own. +* **Testable**: provides a way to submit answers programmatically. +* **Unified**: consistent experience across all [prompts](#-types). + + +![split](https://github.com/terkelg/prompts/raw/master/media/split.png) + + +## ❯ Install + +``` +$ npm install --save prompts +``` + +> This package supports Node 6 and above + +![split](https://github.com/terkelg/prompts/raw/master/media/split.png) + +## ❯ Usage + +example prompt + +```js +const prompts = require('prompts'); + +(async () => { + const response = await prompts({ + type: 'number', + name: 'value', + message: 'How old are you?', + validate: value => value < 18 ? `Nightclub is 18+ only` : true + }); + + console.log(response); // => { value: 24 } +})(); +``` + +> See [`example.js`](https://github.com/terkelg/prompts/blob/master/example.js) for more options. + + +![split](https://github.com/terkelg/prompts/raw/master/media/split.png) + + +## ❯ Examples + +### Single Prompt + +Prompt with a single prompt object. Returns an object with the response. + +```js +const prompts = require('prompts'); + +(async () => { + const response = await prompts({ + type: 'text', + name: 'meaning', + message: 'What is the meaning of life?' + }); + + console.log(response.meaning); +})(); +``` + +### Prompt Chain + +Prompt with a list of prompt objects. Returns an object with the responses. +Make sure to give each prompt a unique `name` property to prevent overwriting values. + +```js +const prompts = require('prompts'); + +const questions = [ + { + type: 'text', + name: 'username', + message: 'What is your GitHub username?' + }, + { + type: 'number', + name: 'age', + message: 'How old are you?' + }, + { + type: 'text', + name: 'about', + message: 'Tell something about yourself', + initial: 'Why should I?' + } +]; + +(async () => { + const response = await prompts(questions); + + // => response => { username, age, about } +})(); +``` + +### Dynamic Prompts + +Prompt properties can be functions too. +Prompt Objects with `type` set to `falsy` values are skipped. + +```js +const prompts = require('prompts'); + +const questions = [ + { + type: 'text', + name: 'dish', + message: 'Do you like pizza?' + }, + { + type: prev => prev == 'pizza' ? 'text' : null, + name: 'topping', + message: 'Name a topping' + } +]; + +(async () => { + const response = await prompts(questions); +})(); +``` + + +![split](https://github.com/terkelg/prompts/raw/master/media/split.png) + + +## ❯ API + +### prompts(prompts, options) + +Type: `Function`
+Returns: `Object` + +Prompter function which takes your [prompt objects](#-prompt-objects) and returns an object with responses. + + +#### prompts + +Type: `Array|Object`
+ +Array of [prompt objects](#-prompt-objects). + These are the questions the user will be prompted. You can see the list of supported [prompt types here](#-types). + +Prompts can be submitted (return, enter) or canceled (esc, abort, ctrl+c, ctrl+d). No property is being defined on the returned response object when a prompt is canceled. + +#### options.onSubmit + +Type: `Function`
+Default: `() => {}` + +Callback that's invoked after each prompt submission. +Its signature is `(prompt, answer, answers)` where `prompt` is the current prompt object, `answer` the user answer to the current question and `answers` the user answers so far. Async functions are supported. + +Return `true` to quit the prompt chain and return all collected responses so far, otherwise continue to iterate prompt objects. + +**Example:** +```js +(async () => { + const questions = [{ ... }]; + const onSubmit = (prompt, answer) => console.log(`Thanks I got ${answer} from ${prompt.name}`); + const response = await prompts(questions, { onSubmit }); +})(); +``` + +#### options.onCancel + +Type: `Function`
+Default: `() => {}` + +Callback that's invoked when the user cancels/exits the prompt. +Its signature is `(prompt, answers)` where `prompt` is the current prompt object and `answers` the user answers so far. Async functions are supported. + +Return `true` to continue and prevent the prompt loop from aborting. +On cancel responses collected so far are returned. + +**Example:** +```js +(async () => { + const questions = [{ ... }]; + const onCancel = prompt => { + console.log('Never stop prompting!'); + return true; + } + const response = await prompts(questions, { onCancel }); +})(); +``` + +### override + +Type: `Function` + +Preanswer questions by passing an object with answers to `prompts.override`. +Powerful when combined with arguments of process. + +**Example** +```js +const prompts = require('prompts'); +prompts.override(require('yargs').argv); + +(async () => { + const response = await prompts([ + { + type: 'text', + name: 'twitter', + message: `What's your twitter handle?` + }, + { + type: 'multiselect', + name: 'color', + message: 'Pick colors', + choices: [ + { title: 'Red', value: '#ff0000' }, + { title: 'Green', value: '#00ff00' }, + { title: 'Blue', value: '#0000ff' } + ], + } + ]); + + console.log(response); +})(); +``` + +### inject(values) + +Type: `Function`
+ +Programmatically inject responses. This enables you to prepare the responses ahead of time. +If any injected value is found the prompt is immediately resolved with the injected value. +This feature is intended for testing only. + +#### values + +Type: `Array` + +Array with values to inject. Resolved values are removed from the internal inject array. +Each value can be an array of values in order to provide answers for a question asked multiple times. +If a value is an instance of `Error` it will simulate the user cancelling/exiting the prompt. + +**Example:** +```js +const prompts = require('prompts'); + +prompts.inject([ '@terkelg', ['#ff0000', '#0000ff'] ]); + +(async () => { + const response = await prompts([ + { + type: 'text', + name: 'twitter', + message: `What's your twitter handle?` + }, + { + type: 'multiselect', + name: 'color', + message: 'Pick colors', + choices: [ + { title: 'Red', value: '#ff0000' }, + { title: 'Green', value: '#00ff00' }, + { title: 'Blue', value: '#0000ff' } + ], + } + ]); + + // => { twitter: 'terkelg', color: [ '#ff0000', '#0000ff' ] } +})(); +``` + +![split](https://github.com/terkelg/prompts/raw/master/media/split.png) + + +## ❯ Prompt Objects + +Prompts Objects are JavaScript objects that define the "questions" and the [type of prompt](#-types). +Almost all prompt objects have the following properties: + +```js +{ + type: String | Function, + name: String | Function, + message: String | Function, + initial: String | Function | Async Function + format: Function | Async Function, + onRender: Function + onState: Function + stdin: Readable + stdout: Writeable +} +``` + +Each property be of type `function` and will be invoked right before prompting the user. + +The function signature is `(prev, values, prompt)`, where `prev` is the value from the previous prompt, +`values` is the response object with all values collected so far and `prompt` is the previous prompt object. + +**Function example:** +```js +{ + type: prev => prev > 3 ? 'confirm' : null, + name: 'confirm', + message: (prev, values) => `Please confirm that you eat ${values.dish} times ${prev} a day?` +} +``` + +The above prompt will be skipped if the value of the previous prompt is less than 3. + +### type + +Type: `String|Function` + +Defines the type of prompt to display. See the list of [prompt types](#-types) for valid values. + +If `type` is a falsy value the prompter will skip that question. +```js +{ + type: null, + name: 'forgetme', + message: `I'll never be shown anyway`, +} +``` + +### name + +Type: `String|Function` + +The response will be saved under this key/property in the returned response object. +In case you have multiple prompts with the same name only the latest response will be stored. + +> Make sure to give prompts unique names if you don't want to overwrite previous values. + +### message + +Type: `String|Function` + +The message to be displayed to the user. + +### initial + +Type: `String|Function` + +Optional default prompt value. Async functions are supported too. + +### format + +Type: `Function` + +Receive the user input and return the formatted value to be used inside the program. +The value returned will be added to the response object. + +The function signature is `(val, values)`, where `val` is the value from the current prompt and +`values` is the current response object in case you need to format based on previous responses. + +**Example:** +```js +{ + type: 'number', + name: 'price', + message: 'Enter price', + format: val => Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(val); +} +``` + +### onRender + +Type: `Function` + +Callback for when the prompt is rendered. +The function receives [kleur](https://github.com/lukeed/kleur) as its first argument and `this` refers to the current prompt. + +**Example:** +```js +{ + type: 'number', + message: 'This message will be overridden', + onRender(kleur) { + this.msg = kleur.cyan('Enter a number'); + } +} +``` + +### onState + +Type: `Function` + +Callback for when the state of the current prompt changes. +The function signature is `(state)` where `state` is an object with a snapshot of the current state. +The state object has two properties `value` and `aborted`. E.g `{ value: 'This is ', aborted: false }` + +### stdin and stdout + +Type: `Stream` + +By default, prompts uses `process.stdin` for receiving input and `process.stdout` for writing output. +If you need to use different streams, for instance `process.stderr`, you can set these with the `stdin` and `stdout` properties. + + +![split](https://github.com/terkelg/prompts/raw/master/media/split.png) + + +## ❯ Types + +* [text](#textmessage-initial-style) +* [password](#passwordmessage-initial) +* [invisible](#invisiblemessage-initial) +* [number](#numbermessage-initial-max-min-style) +* [confirm](#confirmmessage-initial) +* [list](#listmessage-initial) +* [toggle](#togglemessage-initial-active-inactive) +* [select](#selectmessage-choices-initial-hint-warn) +* [multiselect](#multiselectmessage-choices-initial-max-hint-warn) +* [autocompleteMultiselect](#multiselectmessage-choices-initial-max-hint-warn) +* [autocomplete](#autocompletemessage-choices-initial-suggest-limit-style) +* [date](#datemessage-initial-warn) + +*** + +### text(message, [initial], [style]) +> Text prompt for free text input. + +Hit tab to autocomplete to `initial` value when provided. + +#### Example +text prompt + +```js +{ + type: 'text', + name: 'value', + message: `What's your twitter handle?` +} +``` + +#### Options +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| initial | `string` | Default string value | +| style | `string` | Render style (`default`, `password`, `invisible`, `emoji`). Defaults to `default` | +| format | `function` | Receive user input. The returned value will be added to the response object | +| validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | + +**↑ back to:** [Prompt types](#-types) + +*** + +### password(message, [initial]) +> Password prompt with masked input. + +This prompt is a similar to a prompt of type `'text'` with `style` set to `'password'`. + +#### Example +password prompt + +```js +{ + type: 'password', + name: 'value', + message: 'Tell me a secret' +} +``` + +#### Options +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| initial | `string` | Default string value | +| format | `function` | Receive user input. The returned value will be added to the response object | +| validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | + +**↑ back to:** [Prompt types](#-types) + +*** + +### invisible(message, [initial]) +> Prompts user for invisible text input. + +This prompt is working like `sudo` where the input is invisible. +This prompt is a similar to a prompt of type `'text'` with style set to `'invisible'`. + +#### Example +invisible prompt + +```js +{ + type: 'invisible', + name: 'value', + message: 'Enter password' +} +``` + +#### Options +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| initial | `string` | Default string value | +| format | `function` | Receive user input. The returned value will be added to the response object | +| validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | + +**↑ back to:** [Prompt types](#-types) + +*** + +### number(message, initial, [max], [min], [style]) +> Prompts user for number input. + +You can type in numbers and use up/down to increase/decrease the value. Only numbers are allowed as input. Hit tab to autocomplete to `initial` value when provided. + +#### Example +number prompt + +```js +{ + type: 'number', + name: 'value', + message: 'How old are you?', + initial: 0, + style: 'default', + min: 2, + max: 10 +} +``` + +#### Options +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| initial | `number` | Default number value | +| format | `function` | Receive user input. The returned value will be added to the response object | +| validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown | +| max | `number` | Max value. Defaults to `Infinity` | +| min | `number` | Min value. Defaults to `-infinity` | +| float | `boolean` | Allow floating point inputs. Defaults to `false` | +| round | `number` | Round `float` values to x decimals. Defaults to `2` | +| increment | `number` | Increment step when using arrow keys. Defaults to `1` | +| style | `string` | Render style (`default`, `password`, `invisible`, `emoji`). Defaults to `default` | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | + +**↑ back to:** [Prompt types](#-types) + +*** + +### confirm(message, [initial]) +> Classic yes/no prompt. + +Hit y or n to confirm/reject. + +#### Example +confirm prompt + +```js +{ + type: 'confirm', + name: 'value', + message: 'Can you confirm?', + initial: true +} +``` + + +#### Options +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| initial | `boolean` | Default value. Default is `false` | +| format | `function` | Receive user input. The returned value will be added to the response object | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | + +**↑ back to:** [Prompt types](#-types) + +*** + +### list(message, [initial]) +> List prompt that return an array. + +Similar to the `text` prompt, but the output is an `Array` containing the +string separated by `separator`. + +```js +{ + type: 'list', + name: 'value', + message: 'Enter keywords', + initial: '', + separator: ',' +} +``` + +list prompt + + +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| initial | `boolean` | Default value | +| format | `function` | Receive user input. The returned value will be added to the response object | +| separator | `string` | String separator. Will trim all white-spaces from start and end of string. Defaults to `','` | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | + +**↑ back to:** [Prompt types](#-types) + +*** + +### toggle(message, [initial], [active], [inactive]) +> Interactive toggle/switch prompt. + +Use tab or arrow keys/tab/space to switch between options. + +#### Example +toggle prompt + +```js +{ + type: 'toggle', + name: 'value', + message: 'Can you confirm?', + initial: true, + active: 'yes', + inactive: 'no' +} +``` + +#### Options +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| initial | `boolean` | Default value. Defaults to `false` | +| format | `function` | Receive user input. The returned value will be added to the response object | +| active | `string` | Text for `active` state. Defaults to `'on'` | +| inactive | `string` | Text for `inactive` state. Defaults to `'off'` | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | + +**↑ back to:** [Prompt types](#-types) + +*** + +### select(message, choices, [initial], [hint], [warn]) +> Interactive select prompt. + +Use up/down to navigate. Use tab to cycle the list. + +#### Example +select prompt + +```js +{ + type: 'select', + name: 'value', + message: 'Pick a color', + choices: [ + { title: 'Red', description: 'This option has a description', value: '#ff0000' }, + { title: 'Green', value: '#00ff00', disabled: true }, + { title: 'Blue', value: '#0000ff' } + ], + initial: 1 +} +``` + +#### Options +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| initial | `number` | Index of default value | +| format | `function` | Receive user input. The returned value will be added to the response object | +| hint | `string` | Hint to display to the user | +| warn | `string` | Message to display when selecting a disabled option | +| choices | `Array` | Array of strings or choices objects `[{ title, description, value, disabled }, ...]`. The choice's index in the array will be used as its value if it is not specified. | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | + +**↑ back to:** [Prompt types](#-types) + +*** + +### multiselect(message, choices, [initial], [max], [hint], [warn]) +### autocompleteMultiselect(same) +> Interactive multi-select prompt. +> Autocomplete is a searchable multiselect prompt with the same options. Useful for long lists. + +Use space to toggle select/unselect and up/down to navigate. Use tab to cycle the list. You can also use right to select and left to deselect. +By default this prompt returns an `array` containing the **values** of the selected items - not their display title. + +#### Example +multiselect prompt + +```js +{ + type: 'multiselect', + name: 'value', + message: 'Pick colors', + choices: [ + { title: 'Red', value: '#ff0000' }, + { title: 'Green', value: '#00ff00', disabled: true }, + { title: 'Blue', value: '#0000ff', selected: true } + ], + max: 2, + hint: '- Space to select. Return to submit' +} +``` + +#### Options +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| format | `function` | Receive user input. The returned value will be added to the response object | +| instructions | `string` or `boolean` | Prompt instructions to display | +| choices | `Array` | Array of strings or choices objects `[{ title, value, disabled }, ...]`. The choice's index in the array will be used as its value if it is not specified. | +| optionsPerPage | `number` | Number of options displayed per page (default: 10) | +| min | `number` | Min select - will display error | +| max | `number` | Max select | +| hint | `string` | Hint to display to the user | +| warn | `string` | Message to display when selecting a disabled option | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | + +This is one of the few prompts that don't take a initial value. +If you want to predefine selected values, give the choice object an `selected` property of `true`. + +**↑ back to:** [Prompt types](#-types) + +*** + +### autocomplete(message, choices, [initial], [suggest], [limit], [style]) +> Interactive auto complete prompt. + +The prompt will list options based on user input. Type to filter the list. +Use / to navigate. Use tab to cycle the result. Use Page Up/Page Down (on Mac: fn + / ) to change page. Hit enter to select the highlighted item below the prompt. + +The default suggests function is sorting based on the `title` property of the choices. +You can overwrite how choices are being filtered by passing your own suggest function. + +#### Example +auto complete prompt + +```js +{ + type: 'autocomplete', + name: 'value', + message: 'Pick your favorite actor', + choices: [ + { title: 'Cage' }, + { title: 'Clooney', value: 'silver-fox' }, + { title: 'Gyllenhaal' }, + { title: 'Gibson' }, + { title: 'Grant' } + ] +} +``` + +#### Options +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| format | `function` | Receive user input. The returned value will be added to the response object | +| choices | `Array` | Array of auto-complete choices objects `[{ title, value }, ...]` | +| suggest | `function` | Filter function. Defaults to sort by `title` property. `suggest` should always return a promise. Filters using `title` by default | +| limit | `number` | Max number of results to show. Defaults to `10` | +| style | `string` | Render style (`default`, `password`, `invisible`, `emoji`). Defaults to `'default'` | +| initial | `string \| number` | Default initial value | +| clearFirst | `boolean` | The first ESCAPE keypress will clear the input | +| fallback | `string` | Fallback message when no match is found. Defaults to `initial` value if provided | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with three properties: `value`, `aborted` and `exited` | + +Example on what a `suggest` function might look like: +```js +const suggestByTitle = (input, choices) => + Promise.resolve(choices.filter(i => i.title.slice(0, input.length) === input)) +``` + +**↑ back to:** [Prompt types](#-types) + +*** + +### date(message, [initial], [warn]) +> Interactive date prompt. + +Use left/right/tab to navigate. Use up/down to change date. + +#### Example +date prompt + +```js +{ + type: 'date', + name: 'value', + message: 'Pick a date', + initial: new Date(1997, 09, 12), + validate: date => date > Date.now() ? 'Not in the future' : true +} +``` + +#### Options +| Param | Type | Description | +| ----- | :--: | ----------- | +| message | `string` | Prompt message to display | +| initial | `date` | Default date | +| locales | `object` | Use to define custom locales. See below for an example. | +| mask | `string` | The format mask of the date. See below for more information.
Default: `YYYY-MM-DD HH:mm:ss` | +| validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown | +| onRender | `function` | On render callback. Keyword `this` refers to the current prompt | +| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | + +Default locales: + +```javascript +{ + months: [ + 'January', 'February', 'March', 'April', + 'May', 'June', 'July', 'August', + 'September', 'October', 'November', 'December' + ], + monthsShort: [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ], + weekdays: [ + 'Sunday', 'Monday', 'Tuesday', 'Wednesday', + 'Thursday', 'Friday', 'Saturday' + ], + weekdaysShort: [ + 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' + ] +} +``` +>**Formatting**: See full list of formatting options in the [wiki](https://github.com/terkelg/prompts/wiki/Date-Time-Formatting) + +![split](https://github.com/terkelg/prompts/raw/master/media/split.png) + +**↑ back to:** [Prompt types](#-types) + +*** + +## ❯ Credit +Many of the prompts are based on the work of [derhuerst](https://github.com/derhuerst). + + +## ❯ License + +MIT © [Terkel Gjervig](https://terkel.com) diff --git a/node_modules/react-is/LICENSE b/node_modules/react-is/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/react-is/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +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/react-is/README.md b/node_modules/react-is/README.md new file mode 100644 index 0000000..d255977 --- /dev/null +++ b/node_modules/react-is/README.md @@ -0,0 +1,104 @@ +# `react-is` + +This package allows you to test arbitrary values and see if they're a particular React element type. + +## Installation + +```sh +# Yarn +yarn add react-is + +# NPM +npm install react-is +``` + +## Usage + +### Determining if a Component is Valid + +```js +import React from "react"; +import * as ReactIs from "react-is"; + +class ClassComponent extends React.Component { + render() { + return React.createElement("div"); + } +} + +const FunctionComponent = () => React.createElement("div"); + +const ForwardRefComponent = React.forwardRef((props, ref) => + React.createElement(Component, { forwardedRef: ref, ...props }) +); + +const Context = React.createContext(false); + +ReactIs.isValidElementType("div"); // true +ReactIs.isValidElementType(ClassComponent); // true +ReactIs.isValidElementType(FunctionComponent); // true +ReactIs.isValidElementType(ForwardRefComponent); // true +ReactIs.isValidElementType(Context.Provider); // true +ReactIs.isValidElementType(Context.Consumer); // true +ReactIs.isValidElementType(React.createFactory("div")); // true +``` + +### Determining an Element's Type + +#### Context + +```js +import React from "react"; +import * as ReactIs from 'react-is'; + +const ThemeContext = React.createContext("blue"); + +ReactIs.isContextConsumer(); // true +ReactIs.isContextProvider(); // true +ReactIs.typeOf() === ReactIs.ContextProvider; // true +ReactIs.typeOf() === ReactIs.ContextConsumer; // true +``` + +#### Element + +```js +import React from "react"; +import * as ReactIs from 'react-is'; + +ReactIs.isElement(
); // true +ReactIs.typeOf(
) === ReactIs.Element; // true +``` + +#### Fragment + +```js +import React from "react"; +import * as ReactIs from 'react-is'; + +ReactIs.isFragment(<>); // true +ReactIs.typeOf(<>) === ReactIs.Fragment; // true +``` + +#### Portal + +```js +import React from "react"; +import ReactDOM from "react-dom"; +import * as ReactIs from 'react-is'; + +const div = document.createElement("div"); +const portal = ReactDOM.createPortal(
, div); + +ReactIs.isPortal(portal); // true +ReactIs.typeOf(portal) === ReactIs.Portal; // true +``` + +#### StrictMode + +```js +import React from "react"; +import * as ReactIs from 'react-is'; + +ReactIs.isStrictMode(); // true +ReactIs.typeOf() === ReactIs.StrictMode; // true +``` diff --git a/node_modules/react-is/build-info.json b/node_modules/react-is/build-info.json new file mode 100644 index 0000000..db5dbe5 --- /dev/null +++ b/node_modules/react-is/build-info.json @@ -0,0 +1,8 @@ +{ + "branch": "pull/21051", + "buildNumber": "287151", + "checksum": "94f5c65", + "commit": "12adaffef", + "environment": "ci", + "reactVersion": "17.0.0-12adaffef" +} diff --git a/node_modules/react-is/cjs/react-is.development.js b/node_modules/react-is/cjs/react-is.development.js new file mode 100644 index 0000000..b2e388e --- /dev/null +++ b/node_modules/react-is/cjs/react-is.development.js @@ -0,0 +1,226 @@ +/** @license React v17.0.2 + * react-is.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. If there is no native Symbol +// nor polyfill, then a plain number is used for performance. +var REACT_ELEMENT_TYPE = 0xeac7; +var REACT_PORTAL_TYPE = 0xeaca; +var REACT_FRAGMENT_TYPE = 0xeacb; +var REACT_STRICT_MODE_TYPE = 0xeacc; +var REACT_PROFILER_TYPE = 0xead2; +var REACT_PROVIDER_TYPE = 0xeacd; +var REACT_CONTEXT_TYPE = 0xeace; +var REACT_FORWARD_REF_TYPE = 0xead0; +var REACT_SUSPENSE_TYPE = 0xead1; +var REACT_SUSPENSE_LIST_TYPE = 0xead8; +var REACT_MEMO_TYPE = 0xead3; +var REACT_LAZY_TYPE = 0xead4; +var REACT_BLOCK_TYPE = 0xead9; +var REACT_SERVER_BLOCK_TYPE = 0xeada; +var REACT_FUNDAMENTAL_TYPE = 0xead5; +var REACT_SCOPE_TYPE = 0xead7; +var REACT_OPAQUE_ID_TYPE = 0xeae0; +var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; +var REACT_OFFSCREEN_TYPE = 0xeae2; +var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; + +if (typeof Symbol === 'function' && Symbol.for) { + var symbolFor = Symbol.for; + REACT_ELEMENT_TYPE = symbolFor('react.element'); + REACT_PORTAL_TYPE = symbolFor('react.portal'); + REACT_FRAGMENT_TYPE = symbolFor('react.fragment'); + REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); + REACT_PROFILER_TYPE = symbolFor('react.profiler'); + REACT_PROVIDER_TYPE = symbolFor('react.provider'); + REACT_CONTEXT_TYPE = symbolFor('react.context'); + REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); + REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); + REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); + REACT_MEMO_TYPE = symbolFor('react.memo'); + REACT_LAZY_TYPE = symbolFor('react.lazy'); + REACT_BLOCK_TYPE = symbolFor('react.block'); + REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); + REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); + REACT_SCOPE_TYPE = symbolFor('react.scope'); + REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); + REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); + REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); + REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); +} + +// Filter certain DOM attributes (e.g. src, href) if their values are empty strings. + +var enableScopeAPI = false; // Experimental Create Event Handle API. + +function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) { + return true; + } + + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) { + return true; + } + } + + return false; +} + +function typeOf(object) { + if (typeof object === 'object' && object !== null) { + var $$typeof = object.$$typeof; + + switch ($$typeof) { + case REACT_ELEMENT_TYPE: + var type = object.type; + + switch (type) { + case REACT_FRAGMENT_TYPE: + case REACT_PROFILER_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_SUSPENSE_TYPE: + case REACT_SUSPENSE_LIST_TYPE: + return type; + + default: + var $$typeofType = type && type.$$typeof; + + switch ($$typeofType) { + case REACT_CONTEXT_TYPE: + case REACT_FORWARD_REF_TYPE: + case REACT_LAZY_TYPE: + case REACT_MEMO_TYPE: + case REACT_PROVIDER_TYPE: + return $$typeofType; + + default: + return $$typeof; + } + + } + + case REACT_PORTAL_TYPE: + return $$typeof; + } + } + + return undefined; +} +var ContextConsumer = REACT_CONTEXT_TYPE; +var ContextProvider = REACT_PROVIDER_TYPE; +var Element = REACT_ELEMENT_TYPE; +var ForwardRef = REACT_FORWARD_REF_TYPE; +var Fragment = REACT_FRAGMENT_TYPE; +var Lazy = REACT_LAZY_TYPE; +var Memo = REACT_MEMO_TYPE; +var Portal = REACT_PORTAL_TYPE; +var Profiler = REACT_PROFILER_TYPE; +var StrictMode = REACT_STRICT_MODE_TYPE; +var Suspense = REACT_SUSPENSE_TYPE; +var hasWarnedAboutDeprecatedIsAsyncMode = false; +var hasWarnedAboutDeprecatedIsConcurrentMode = false; // AsyncMode should be deprecated + +function isAsyncMode(object) { + { + if (!hasWarnedAboutDeprecatedIsAsyncMode) { + hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); + } + } + + return false; +} +function isConcurrentMode(object) { + { + if (!hasWarnedAboutDeprecatedIsConcurrentMode) { + hasWarnedAboutDeprecatedIsConcurrentMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isConcurrentMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); + } + } + + return false; +} +function isContextConsumer(object) { + return typeOf(object) === REACT_CONTEXT_TYPE; +} +function isContextProvider(object) { + return typeOf(object) === REACT_PROVIDER_TYPE; +} +function isElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; +} +function isForwardRef(object) { + return typeOf(object) === REACT_FORWARD_REF_TYPE; +} +function isFragment(object) { + return typeOf(object) === REACT_FRAGMENT_TYPE; +} +function isLazy(object) { + return typeOf(object) === REACT_LAZY_TYPE; +} +function isMemo(object) { + return typeOf(object) === REACT_MEMO_TYPE; +} +function isPortal(object) { + return typeOf(object) === REACT_PORTAL_TYPE; +} +function isProfiler(object) { + return typeOf(object) === REACT_PROFILER_TYPE; +} +function isStrictMode(object) { + return typeOf(object) === REACT_STRICT_MODE_TYPE; +} +function isSuspense(object) { + return typeOf(object) === REACT_SUSPENSE_TYPE; +} + +exports.ContextConsumer = ContextConsumer; +exports.ContextProvider = ContextProvider; +exports.Element = Element; +exports.ForwardRef = ForwardRef; +exports.Fragment = Fragment; +exports.Lazy = Lazy; +exports.Memo = Memo; +exports.Portal = Portal; +exports.Profiler = Profiler; +exports.StrictMode = StrictMode; +exports.Suspense = Suspense; +exports.isAsyncMode = isAsyncMode; +exports.isConcurrentMode = isConcurrentMode; +exports.isContextConsumer = isContextConsumer; +exports.isContextProvider = isContextProvider; +exports.isElement = isElement; +exports.isForwardRef = isForwardRef; +exports.isFragment = isFragment; +exports.isLazy = isLazy; +exports.isMemo = isMemo; +exports.isPortal = isPortal; +exports.isProfiler = isProfiler; +exports.isStrictMode = isStrictMode; +exports.isSuspense = isSuspense; +exports.isValidElementType = isValidElementType; +exports.typeOf = typeOf; + })(); +} diff --git a/node_modules/react-is/cjs/react-is.production.min.js b/node_modules/react-is/cjs/react-is.production.min.js new file mode 100644 index 0000000..b416090 --- /dev/null +++ b/node_modules/react-is/cjs/react-is.production.min.js @@ -0,0 +1,14 @@ +/** @license React v17.0.2 + * react-is.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var b=60103,c=60106,d=60107,e=60108,f=60114,g=60109,h=60110,k=60112,l=60113,m=60120,n=60115,p=60116,q=60121,r=60122,u=60117,v=60129,w=60131; +if("function"===typeof Symbol&&Symbol.for){var x=Symbol.for;b=x("react.element");c=x("react.portal");d=x("react.fragment");e=x("react.strict_mode");f=x("react.profiler");g=x("react.provider");h=x("react.context");k=x("react.forward_ref");l=x("react.suspense");m=x("react.suspense_list");n=x("react.memo");p=x("react.lazy");q=x("react.block");r=x("react.server.block");u=x("react.fundamental");v=x("react.debug_trace_mode");w=x("react.legacy_hidden")} +function y(a){if("object"===typeof a&&null!==a){var t=a.$$typeof;switch(t){case b:switch(a=a.type,a){case d:case f:case e:case l:case m:return a;default:switch(a=a&&a.$$typeof,a){case h:case k:case p:case n:case g:return a;default:return t}}case c:return t}}}var z=g,A=b,B=k,C=d,D=p,E=n,F=c,G=f,H=e,I=l;exports.ContextConsumer=h;exports.ContextProvider=z;exports.Element=A;exports.ForwardRef=B;exports.Fragment=C;exports.Lazy=D;exports.Memo=E;exports.Portal=F;exports.Profiler=G;exports.StrictMode=H; +exports.Suspense=I;exports.isAsyncMode=function(){return!1};exports.isConcurrentMode=function(){return!1};exports.isContextConsumer=function(a){return y(a)===h};exports.isContextProvider=function(a){return y(a)===g};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===b};exports.isForwardRef=function(a){return y(a)===k};exports.isFragment=function(a){return y(a)===d};exports.isLazy=function(a){return y(a)===p};exports.isMemo=function(a){return y(a)===n}; +exports.isPortal=function(a){return y(a)===c};exports.isProfiler=function(a){return y(a)===f};exports.isStrictMode=function(a){return y(a)===e};exports.isSuspense=function(a){return y(a)===l};exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===d||a===f||a===v||a===e||a===l||a===m||a===w||"object"===typeof a&&null!==a&&(a.$$typeof===p||a.$$typeof===n||a.$$typeof===g||a.$$typeof===h||a.$$typeof===k||a.$$typeof===u||a.$$typeof===q||a[0]===r)?!0:!1}; +exports.typeOf=y; diff --git a/node_modules/react-is/index.js b/node_modules/react-is/index.js new file mode 100644 index 0000000..3ae098d --- /dev/null +++ b/node_modules/react-is/index.js @@ -0,0 +1,7 @@ +'use strict'; + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./cjs/react-is.production.min.js'); +} else { + module.exports = require('./cjs/react-is.development.js'); +} diff --git a/node_modules/react-is/package.json b/node_modules/react-is/package.json new file mode 100644 index 0000000..1a6567d --- /dev/null +++ b/node_modules/react-is/package.json @@ -0,0 +1,27 @@ +{ + "name": "react-is", + "version": "17.0.2", + "description": "Brand checking of React Elements.", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/facebook/react.git", + "directory": "packages/react-is" + }, + "keywords": [ + "react" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/facebook/react/issues" + }, + "homepage": "https://reactjs.org/", + "files": [ + "LICENSE", + "README.md", + "build-info.json", + "index.js", + "cjs/", + "umd/" + ] +} diff --git a/node_modules/react-is/umd/react-is.development.js b/node_modules/react-is/umd/react-is.development.js new file mode 100644 index 0000000..cc44c5b --- /dev/null +++ b/node_modules/react-is/umd/react-is.development.js @@ -0,0 +1,225 @@ +/** @license React v17.0.2 + * react-is.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.ReactIs = {})); +}(this, (function (exports) { 'use strict'; + + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. If there is no native Symbol + // nor polyfill, then a plain number is used for performance. + var REACT_ELEMENT_TYPE = 0xeac7; + var REACT_PORTAL_TYPE = 0xeaca; + var REACT_FRAGMENT_TYPE = 0xeacb; + var REACT_STRICT_MODE_TYPE = 0xeacc; + var REACT_PROFILER_TYPE = 0xead2; + var REACT_PROVIDER_TYPE = 0xeacd; + var REACT_CONTEXT_TYPE = 0xeace; + var REACT_FORWARD_REF_TYPE = 0xead0; + var REACT_SUSPENSE_TYPE = 0xead1; + var REACT_SUSPENSE_LIST_TYPE = 0xead8; + var REACT_MEMO_TYPE = 0xead3; + var REACT_LAZY_TYPE = 0xead4; + var REACT_BLOCK_TYPE = 0xead9; + var REACT_SERVER_BLOCK_TYPE = 0xeada; + var REACT_FUNDAMENTAL_TYPE = 0xead5; + var REACT_SCOPE_TYPE = 0xead7; + var REACT_OPAQUE_ID_TYPE = 0xeae0; + var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; + var REACT_OFFSCREEN_TYPE = 0xeae2; + var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; + + if (typeof Symbol === 'function' && Symbol.for) { + var symbolFor = Symbol.for; + REACT_ELEMENT_TYPE = symbolFor('react.element'); + REACT_PORTAL_TYPE = symbolFor('react.portal'); + REACT_FRAGMENT_TYPE = symbolFor('react.fragment'); + REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); + REACT_PROFILER_TYPE = symbolFor('react.profiler'); + REACT_PROVIDER_TYPE = symbolFor('react.provider'); + REACT_CONTEXT_TYPE = symbolFor('react.context'); + REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); + REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); + REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); + REACT_MEMO_TYPE = symbolFor('react.memo'); + REACT_LAZY_TYPE = symbolFor('react.lazy'); + REACT_BLOCK_TYPE = symbolFor('react.block'); + REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); + REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); + REACT_SCOPE_TYPE = symbolFor('react.scope'); + REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); + REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); + REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); + REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); + } + + // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. + + var enableScopeAPI = false; // Experimental Create Event Handle API. + + function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) { + return true; + } + + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) { + return true; + } + } + + return false; + } + + function typeOf(object) { + if (typeof object === 'object' && object !== null) { + var $$typeof = object.$$typeof; + + switch ($$typeof) { + case REACT_ELEMENT_TYPE: + var type = object.type; + + switch (type) { + case REACT_FRAGMENT_TYPE: + case REACT_PROFILER_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_SUSPENSE_TYPE: + case REACT_SUSPENSE_LIST_TYPE: + return type; + + default: + var $$typeofType = type && type.$$typeof; + + switch ($$typeofType) { + case REACT_CONTEXT_TYPE: + case REACT_FORWARD_REF_TYPE: + case REACT_LAZY_TYPE: + case REACT_MEMO_TYPE: + case REACT_PROVIDER_TYPE: + return $$typeofType; + + default: + return $$typeof; + } + + } + + case REACT_PORTAL_TYPE: + return $$typeof; + } + } + + return undefined; + } + var ContextConsumer = REACT_CONTEXT_TYPE; + var ContextProvider = REACT_PROVIDER_TYPE; + var Element = REACT_ELEMENT_TYPE; + var ForwardRef = REACT_FORWARD_REF_TYPE; + var Fragment = REACT_FRAGMENT_TYPE; + var Lazy = REACT_LAZY_TYPE; + var Memo = REACT_MEMO_TYPE; + var Portal = REACT_PORTAL_TYPE; + var Profiler = REACT_PROFILER_TYPE; + var StrictMode = REACT_STRICT_MODE_TYPE; + var Suspense = REACT_SUSPENSE_TYPE; + var hasWarnedAboutDeprecatedIsAsyncMode = false; + var hasWarnedAboutDeprecatedIsConcurrentMode = false; // AsyncMode should be deprecated + + function isAsyncMode(object) { + { + if (!hasWarnedAboutDeprecatedIsAsyncMode) { + hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); + } + } + + return false; + } + function isConcurrentMode(object) { + { + if (!hasWarnedAboutDeprecatedIsConcurrentMode) { + hasWarnedAboutDeprecatedIsConcurrentMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isConcurrentMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); + } + } + + return false; + } + function isContextConsumer(object) { + return typeOf(object) === REACT_CONTEXT_TYPE; + } + function isContextProvider(object) { + return typeOf(object) === REACT_PROVIDER_TYPE; + } + function isElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + function isForwardRef(object) { + return typeOf(object) === REACT_FORWARD_REF_TYPE; + } + function isFragment(object) { + return typeOf(object) === REACT_FRAGMENT_TYPE; + } + function isLazy(object) { + return typeOf(object) === REACT_LAZY_TYPE; + } + function isMemo(object) { + return typeOf(object) === REACT_MEMO_TYPE; + } + function isPortal(object) { + return typeOf(object) === REACT_PORTAL_TYPE; + } + function isProfiler(object) { + return typeOf(object) === REACT_PROFILER_TYPE; + } + function isStrictMode(object) { + return typeOf(object) === REACT_STRICT_MODE_TYPE; + } + function isSuspense(object) { + return typeOf(object) === REACT_SUSPENSE_TYPE; + } + + exports.ContextConsumer = ContextConsumer; + exports.ContextProvider = ContextProvider; + exports.Element = Element; + exports.ForwardRef = ForwardRef; + exports.Fragment = Fragment; + exports.Lazy = Lazy; + exports.Memo = Memo; + exports.Portal = Portal; + exports.Profiler = Profiler; + exports.StrictMode = StrictMode; + exports.Suspense = Suspense; + exports.isAsyncMode = isAsyncMode; + exports.isConcurrentMode = isConcurrentMode; + exports.isContextConsumer = isContextConsumer; + exports.isContextProvider = isContextProvider; + exports.isElement = isElement; + exports.isForwardRef = isForwardRef; + exports.isFragment = isFragment; + exports.isLazy = isLazy; + exports.isMemo = isMemo; + exports.isPortal = isPortal; + exports.isProfiler = isProfiler; + exports.isStrictMode = isStrictMode; + exports.isSuspense = isSuspense; + exports.isValidElementType = isValidElementType; + exports.typeOf = typeOf; + +}))); diff --git a/node_modules/react-is/umd/react-is.production.min.js b/node_modules/react-is/umd/react-is.production.min.js new file mode 100644 index 0000000..126d595 --- /dev/null +++ b/node_modules/react-is/umd/react-is.production.min.js @@ -0,0 +1,14 @@ +/** @license React v17.0.2 + * react-is.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +(function(){'use strict';(function(b,d){"object"===typeof exports&&"undefined"!==typeof module?d(exports):"function"===typeof define&&define.amd?define(["exports"],d):(b=b||self,d(b.ReactIs={}))})(this,function(b){function d(a){if("object"===typeof a&&null!==a){var b=a.$$typeof;switch(b){case q:switch(a=a.type,a){case e:case f:case g:case h:case t:return a;default:switch(a=a&&a.$$typeof,a){case k:case l:case m:case n:case p:return a;default:return b}}case r:return b}}}var q=60103,r=60106,e=60107,g=60108,f=60114, +p=60109,k=60110,l=60112,h=60113,t=60120,n=60115,m=60116,u=60121,v=60122,w=60117,x=60129,y=60131;if("function"===typeof Symbol&&Symbol.for){var c=Symbol.for;q=c("react.element");r=c("react.portal");e=c("react.fragment");g=c("react.strict_mode");f=c("react.profiler");p=c("react.provider");k=c("react.context");l=c("react.forward_ref");h=c("react.suspense");t=c("react.suspense_list");n=c("react.memo");m=c("react.lazy");u=c("react.block");v=c("react.server.block");w=c("react.fundamental");x=c("react.debug_trace_mode"); +y=c("react.legacy_hidden")}b.ContextConsumer=k;b.ContextProvider=p;b.Element=q;b.ForwardRef=l;b.Fragment=e;b.Lazy=m;b.Memo=n;b.Portal=r;b.Profiler=f;b.StrictMode=g;b.Suspense=h;b.isAsyncMode=function(a){return!1};b.isConcurrentMode=function(a){return!1};b.isContextConsumer=function(a){return d(a)===k};b.isContextProvider=function(a){return d(a)===p};b.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===q};b.isForwardRef=function(a){return d(a)===l};b.isFragment=function(a){return d(a)=== +e};b.isLazy=function(a){return d(a)===m};b.isMemo=function(a){return d(a)===n};b.isPortal=function(a){return d(a)===r};b.isProfiler=function(a){return d(a)===f};b.isStrictMode=function(a){return d(a)===g};b.isSuspense=function(a){return d(a)===h};b.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===f||a===x||a===g||a===h||a===t||a===y||"object"===typeof a&&null!==a&&(a.$$typeof===m||a.$$typeof===n||a.$$typeof===p||a.$$typeof===k||a.$$typeof===l||a.$$typeof=== +w||a.$$typeof===u||a[0]===v)?!0:!1};b.typeOf=d}); +})(); diff --git a/node_modules/readdirp/LICENSE b/node_modules/readdirp/LICENSE new file mode 100644 index 0000000..037cbb4 --- /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 0000000..465593c --- /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 0000000..cbbd76c --- /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 0000000..cf739b2 --- /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 0000000..dba5388 --- /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/redent/index.d.ts b/node_modules/redent/index.d.ts new file mode 100644 index 0000000..67b94c7 --- /dev/null +++ b/node_modules/redent/index.d.ts @@ -0,0 +1,27 @@ +import {Options as IndentStringOptions} from 'indent-string'; + +declare namespace redent { + type Options = IndentStringOptions; +} + +/** +[Strip redundant indentation](https://github.com/sindresorhus/strip-indent) and [indent the string](https://github.com/sindresorhus/indent-string). + +@param string - The string to normalize indentation. +@param count - How many times you want `options.indent` repeated. Default: `0`. + +@example +``` +import redent = require('redent'); + +redent('\n foo\n bar\n', 1); +//=> '\n foo\n bar\n' +``` +*/ +declare function redent( + string: string, + count?: number, + options?: redent.Options +): string; + +export = redent; diff --git a/node_modules/redent/index.js b/node_modules/redent/index.js new file mode 100644 index 0000000..9457849 --- /dev/null +++ b/node_modules/redent/index.js @@ -0,0 +1,5 @@ +'use strict'; +const stripIndent = require('strip-indent'); +const indentString = require('indent-string'); + +module.exports = (string, count = 0, options) => indentString(stripIndent(string), count, options); diff --git a/node_modules/redent/license b/node_modules/redent/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/redent/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/redent/package.json b/node_modules/redent/package.json new file mode 100644 index 0000000..89b5021 --- /dev/null +++ b/node_modules/redent/package.json @@ -0,0 +1,44 @@ +{ + "name": "redent", + "version": "3.0.0", + "description": "Strip redundant indentation and indent the string", + "license": "MIT", + "repository": "sindresorhus/redent", + "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": [ + "string", + "strip", + "trim", + "indent", + "indentation", + "add", + "reindent", + "normalize", + "remove", + "whitespace", + "space" + ], + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/redent/readme.md b/node_modules/redent/readme.md new file mode 100644 index 0000000..8a186c2 --- /dev/null +++ b/node_modules/redent/readme.md @@ -0,0 +1,61 @@ +# redent [![Build Status](https://travis-ci.org/sindresorhus/redent.svg?branch=master)](https://travis-ci.org/sindresorhus/redent) + +> [Strip redundant indentation](https://github.com/sindresorhus/strip-indent) and [indent the string](https://github.com/sindresorhus/indent-string) + + +## Install + +``` +$ npm install redent +``` + + +## Usage + +```js +const redent = require('redent'); + +redent('\n foo\n bar\n', 1); +//=> '\n foo\n bar\n' +``` + + +## API + +### redent(string, [count], [options]) + +#### string + +Type: `string` + +The string to normalize indentation. + +#### count + +Type: `number`
+Default: `0` + +How many times you want `options.indent` repeated. + +#### options + +Type: `object` + +##### indent + +Type: `string`
+Default: `' '` + +The string to use for the indent. + +##### includeEmptyLines + +Type: `boolean`
+Default: `false` + +Also indent empty lines. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/regenerator-runtime/LICENSE b/node_modules/regenerator-runtime/LICENSE new file mode 100644 index 0000000..cde61b6 --- /dev/null +++ b/node_modules/regenerator-runtime/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2014-present, Facebook, Inc. + +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/regenerator-runtime/README.md b/node_modules/regenerator-runtime/README.md new file mode 100644 index 0000000..e8702ba --- /dev/null +++ b/node_modules/regenerator-runtime/README.md @@ -0,0 +1,31 @@ +# regenerator-runtime + +Standalone runtime for +[Regenerator](https://github.com/facebook/regenerator)-compiled generator +and `async` functions. + +To import the runtime as a module (recommended), either of the following +import styles will work: +```js +// CommonJS +const regeneratorRuntime = require("regenerator-runtime"); + +// ECMAScript 2015 +import regeneratorRuntime from "regenerator-runtime"; +``` + +To ensure that `regeneratorRuntime` is defined globally, either of the +following styles will work: +```js +// CommonJS +require("regenerator-runtime/runtime"); + +// ECMAScript 2015 +import "regenerator-runtime/runtime.js"; +``` + +To get the absolute file system path of `runtime.js`, evaluate the +following expression: +```js +require("regenerator-runtime/path").path +``` diff --git a/node_modules/regenerator-runtime/package.json b/node_modules/regenerator-runtime/package.json new file mode 100644 index 0000000..5f70491 --- /dev/null +++ b/node_modules/regenerator-runtime/package.json @@ -0,0 +1,19 @@ +{ + "name": "regenerator-runtime", + "author": "Ben Newman ", + "description": "Runtime for Regenerator-compiled generator and async functions.", + "version": "0.13.11", + "main": "runtime.js", + "keywords": [ + "regenerator", + "runtime", + "generator", + "async" + ], + "sideEffects": true, + "repository": { + "type": "git", + "url": "https://github.com/facebook/regenerator/tree/main/packages/runtime" + }, + "license": "MIT" +} diff --git a/node_modules/regenerator-runtime/path.js b/node_modules/regenerator-runtime/path.js new file mode 100644 index 0000000..ced878b --- /dev/null +++ b/node_modules/regenerator-runtime/path.js @@ -0,0 +1,11 @@ +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +exports.path = require("path").join( + __dirname, + "runtime.js" +); diff --git a/node_modules/regenerator-runtime/runtime.js b/node_modules/regenerator-runtime/runtime.js new file mode 100644 index 0000000..1ea704e --- /dev/null +++ b/node_modules/regenerator-runtime/runtime.js @@ -0,0 +1,761 @@ +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +var runtime = (function (exports) { + "use strict"; + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + function define(obj, key, value) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + return obj[key]; + } + try { + // IE 8 has a broken Object.defineProperty that only works on DOM objects. + define({}, ""); + } catch (err) { + define = function(obj, key, value) { + return obj[key] = value; + }; + } + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }); + + return generator; + } + exports.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = GeneratorFunctionPrototype; + defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: true }); + defineProperty( + GeneratorFunctionPrototype, + "constructor", + { value: GeneratorFunction, configurable: true } + ); + GeneratorFunction.displayName = define( + GeneratorFunctionPrototype, + toStringTagSymbol, + "GeneratorFunction" + ); + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + define(prototype, method, function(arg) { + return this._invoke(method, arg); + }); + }); + } + + exports.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + exports.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + define(genFun, toStringTagSymbol, "GeneratorFunction"); + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + exports.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return PromiseImpl.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return PromiseImpl.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. + result.value = unwrapped; + resolve(result); + }, function(error) { + // If a rejected Promise was yielded, throw the rejection back + // into the async generator function so it can be handled there. + return invoke("throw", error, resolve, reject); + }); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + defineProperty(this, "_invoke", { value: enqueue }); + } + + defineIteratorMethods(AsyncIterator.prototype); + define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }); + exports.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { + if (PromiseImpl === void 0) PromiseImpl = Promise; + + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList), + PromiseImpl + ); + + return exports.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var methodName = context.method; + var method = delegate.iterator[methodName]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method, or a missing .next mehtod, always terminate the + // yield* loop. + context.delegate = null; + + // Note: ["return"] must be used for ES3 parsing compatibility. + if (methodName === "throw" && delegate.iterator["return"]) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + if (methodName !== "return") { + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a '" + methodName + "' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + define(Gp, toStringTagSymbol, "Generator"); + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + define(Gp, iteratorSymbol, function() { + return this; + }); + + define(Gp, "toString", function() { + return "[object Generator]"; + }); + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + exports.keys = function(val) { + var object = Object(val); + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + exports.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } + + return ContinueSentinel; + } + }; + + // Regardless of whether this script is executing as a CommonJS module + // or not, return the runtime object so that we can declare the variable + // regeneratorRuntime in the outer scope, which allows this module to be + // injected easily by `bin/regenerator --include-runtime script.js`. + return exports; + +}( + // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + typeof module === "object" ? module.exports : {} +)); + +try { + regeneratorRuntime = runtime; +} catch (accidentalStrictMode) { + // This module should not be running in strict mode, so the above + // assignment should always work unless something is misconfigured. Just + // in case runtime.js accidentally runs in strict mode, in modern engines + // we can explicitly access globalThis. In older engines we can escape + // strict mode using a global Function call. This could conceivably fail + // if a Content Security Policy forbids using Function, but in that case + // the proper solution is to fix the accidental strict mode problem. If + // you've misconfigured your bundler to force strict mode and applied a + // CSP to forbid Function, and you're not willing to fix either of those + // problems, please detail your unique predicament in a GitHub issue. + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); + } +} diff --git a/node_modules/regexp.prototype.flags/.editorconfig b/node_modules/regexp.prototype.flags/.editorconfig new file mode 100644 index 0000000..eaa2141 --- /dev/null +++ b/node_modules/regexp.prototype.flags/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/node_modules/regexp.prototype.flags/.eslintrc b/node_modules/regexp.prototype.flags/.eslintrc new file mode 100644 index 0000000..dcbbda2 --- /dev/null +++ b/node_modules/regexp.prototype.flags/.eslintrc @@ -0,0 +1,19 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "eqeqeq": [2, "allow-null"], + "id-length": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": 0, + }, + }, + ], +} diff --git a/node_modules/regexp.prototype.flags/.nycrc b/node_modules/regexp.prototype.flags/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/regexp.prototype.flags/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/regexp.prototype.flags/CHANGELOG.md b/node_modules/regexp.prototype.flags/CHANGELOG.md new file mode 100644 index 0000000..f7bf7b8 --- /dev/null +++ b/node_modules/regexp.prototype.flags/CHANGELOG.md @@ -0,0 +1,190 @@ +# 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.4.3](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.4.2...v1.4.3) - 2022-04-14 + +### Commits + +- [Fix] when shimmed, name must be `get flags` [`fcefd00`](https://github.com/es-shims/RegExp.prototype.flags/commit/fcefd0039177e9cbcb2ed842d353131ace7a3377) + +## [v1.4.2](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.4.1...v1.4.2) - 2022-04-12 + +### Commits + +- [Fix] ensure `hasIndices` is patched properly, and getter order is correct [`a1af45a`](https://github.com/es-shims/RegExp.prototype.flags/commit/a1af45a8a6f7305b097b83f96ee9fc45abb3e733) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `tape` [`24f5a0c`](https://github.com/es-shims/RegExp.prototype.flags/commit/24f5a0c84f2e7d263ae0e2008def870afd6d5a4f) + +## [v1.4.1](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.4.0...v1.4.1) - 2022-01-13 + +### Commits + +- [Fix] `polyfill`: do not throw in a descriptorless environment [`e2d24e7`](https://github.com/es-shims/RegExp.prototype.flags/commit/e2d24e707a44d958a0b6d3a114effb2f2b475337) + +## [v1.4.0](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.3.2...v1.4.0) - 2022-01-13 + +### Commits + +- [Tests] use `available-regexp-flags` [`95af246`](https://github.com/es-shims/RegExp.prototype.flags/commit/95af2463f1373282087528f8566e20ffae26c3db) +- [New] add `hasIndices`/`d` flag [`89959ca`](https://github.com/es-shims/RegExp.prototype.flags/commit/89959ca1128ea48dcd0ec1416355264425fa3bc5) + +## [v1.3.2](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.3.1...v1.3.2) - 2022-01-13 + +### Commits + +- [actions] reuse common workflows [`6665b5d`](https://github.com/es-shims/RegExp.prototype.flags/commit/6665b5db7c45ce6b987d08ebaf6d2767eec95b94) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`babce94`](https://github.com/es-shims/RegExp.prototype.flags/commit/babce94b5ca96e93e74e384c0a01295943677a3f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `object-inspect`, `safe-publish-latest`, `tape` [`52132d9`](https://github.com/es-shims/RegExp.prototype.flags/commit/52132d9f3df904864d4cf3fd44892ee563aee524) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c16687c`](https://github.com/es-shims/RegExp.prototype.flags/commit/c16687c118d374d8997a8d885467507bf943b4bc) +- [actions] update codecov uploader [`0a3c904`](https://github.com/es-shims/RegExp.prototype.flags/commit/0a3c904a9fd1247b3b8e0fb6b451b3fbe97735bd) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`3fce7f2`](https://github.com/es-shims/RegExp.prototype.flags/commit/3fce7f27c753440003675d03ae9a7ecfa6a74d30) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`75ca498`](https://github.com/es-shims/RegExp.prototype.flags/commit/75ca49889349fc42e51ea79b2ec7a1996fb3eb18) +- [actions] update workflows [`300f321`](https://github.com/es-shims/RegExp.prototype.flags/commit/300f321984526066656bec791f0bb3861b33cfbc) +- [meta] better `eccheck` command [`5f735ab`](https://github.com/es-shims/RegExp.prototype.flags/commit/5f735ab1b1c87dbd05c0096249160587f166cd51) +- [Dev Deps] update `eslint`, `tape` [`3059637`](https://github.com/es-shims/RegExp.prototype.flags/commit/3059637210eb5c9fa97160ec2f0aea1d1d724eb7) +- [actions] update workflows` [`dbd8ab4`](https://github.com/es-shims/RegExp.prototype.flags/commit/dbd8ab49fa2196dd74791107825c43e4481cdfd2) +- [meta] use `prepublishOnly` script for npm 7+ [`5cc8652`](https://github.com/es-shims/RegExp.prototype.flags/commit/5cc86524a41bf358b6701bcf46e480f0e3e470b4) +- [Fix] use polyfill, not implementation, in main export [`15ab4b8`](https://github.com/es-shims/RegExp.prototype.flags/commit/15ab4b85f3904e48664e26394dc12765ed666da4) +- [meta] remove `audit-level` config, which breaks npm 7 installs [`1cb98ae`](https://github.com/es-shims/RegExp.prototype.flags/commit/1cb98aed731e73d11df5ed3b853b371d35a69f5a) + +## [v1.3.1](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.3.0...v1.3.1) - 2021-01-15 + +### Commits + +- [Tests] run `nyc` on all tests; use `tape` runner; add full es-shims test suite [`047a1e8`](https://github.com/es-shims/RegExp.prototype.flags/commit/047a1e8ff250220254b0e9598d962a56c8ec3ffc) +- [Tests] migrate tests to Github Actions [`e4e391f`](https://github.com/es-shims/RegExp.prototype.flags/commit/e4e391fd3e6f057172994ad0c33ca128568c0b06) +- [meta] use `auto-changelog` for changelog [`afbcd06`](https://github.com/es-shims/RegExp.prototype.flags/commit/afbcd06402e97e975af797e2c1375e35e22e90f2) +- [actions] add Require Allow Edits workflow [`0db5d50`](https://github.com/es-shims/RegExp.prototype.flags/commit/0db5d50cdf59e3e5529024af4f8ce05829edc06d) +- [meta] do not publish github action workflow files [`53f2902`](https://github.com/es-shims/RegExp.prototype.flags/commit/53f29020e5a1f517e91b8cf226ed6bc97eadc090) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`; add `aud` [`05f2a85`](https://github.com/es-shims/RegExp.prototype.flags/commit/05f2a851869069c7911176809028be8491465f86) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`2a197b8`](https://github.com/es-shims/RegExp.prototype.flags/commit/2a197b84916f094946c5cad56ef8e7bb7e8f12ac) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`; add `safe-publish-latest` [`e40bd37`](https://github.com/es-shims/RegExp.prototype.flags/commit/e40bd37de9bb756672832a6c994652965d09b9ae) +- [Refactor] use `call-bind` instead of `es-abstract` [`e6eac90`](https://github.com/es-shims/RegExp.prototype.flags/commit/e6eac9052ebdb4bc28cb83b5d3017a4ed74fe3f1) +- [Deps] update `es-abstract` [`f198075`](https://github.com/es-shims/RegExp.prototype.flags/commit/f198075d6fc075e0d98967af98a512742e6e7e4f) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`2d21727`](https://github.com/es-shims/RegExp.prototype.flags/commit/2d217275d78214b82c7f5cacca85ca2308df83f1) +- [Deps] update `es-abstract` [`7e7ddc6`](https://github.com/es-shims/RegExp.prototype.flags/commit/7e7ddc66174256f6688a857b09c9a02bafcf4866) + +## [v1.3.0](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.2.0...v1.3.0) - 2019-12-14 + +### Commits + +- [Tests] remove `jscs` [`4a09ab4`](https://github.com/es-shims/RegExp.prototype.flags/commit/4a09ab467f62065a1718b0dcc50f7818b5400ab6) +- [Tests] use shared travis-ci configs [`8afa6a9`](https://github.com/es-shims/RegExp.prototype.flags/commit/8afa6a99fd35c19fb49ba630fd17159a5da2a34e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `has`, `tape` [`13a9fc9`](https://github.com/es-shims/RegExp.prototype.flags/commit/13a9fc9d6bc2600681eb3f638668beccf80b843c) +- [Refactor] use `callBind` helper from `es-abstract` [`c3a3727`](https://github.com/es-shims/RegExp.prototype.flags/commit/c3a37276764d99c1e4f7e9467ad636fce8c92c58) +- [actions] add automatic rebasing / merge commit blocking [`51e3f93`](https://github.com/es-shims/RegExp.prototype.flags/commit/51e3f9366d15a07edaf532884948ce74b6827125) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`7e1ee50`](https://github.com/es-shims/RegExp.prototype.flags/commit/7e1ee505df374867c2c04d500aa1c36265161b6f) +- [meta] add `funding` field [`c99cbec`](https://github.com/es-shims/RegExp.prototype.flags/commit/c99cbec1af9b0e0be42e82f164adacf2e1bdee16) +- [New] add `auto` entry point [`1e53e85`](https://github.com/es-shims/RegExp.prototype.flags/commit/1e53e854f663472e74dd0350e0c095df9c2b9c7b) +- [Tests] use `eclint` instead of `editorconfig-tools` [`8600bfe`](https://github.com/es-shims/RegExp.prototype.flags/commit/8600bfed42ab8d294463df482874c344fc079f82) +- [Deps] update `define-properties` [`ad221fa`](https://github.com/es-shims/RegExp.prototype.flags/commit/ad221fa2a26a9c2bc8d274b689cf7a626b58f4e9) + +## [v1.2.0](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.1.1...v1.2.0) - 2017-10-24 + +### Commits + +- [Tests] up to `node` `v8.8`, `v7.10`, `v6.11`, `v4.8`; improve matrix; use `nvm install-latest-npm` so new npm doesn’t break old node [`5a9653d`](https://github.com/es-shims/RegExp.prototype.flags/commit/5a9653d1904eb8ad8baffe43cd065b6f36013e5a) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`; add `has` [`556de86`](https://github.com/es-shims/RegExp.prototype.flags/commit/556de8632bbe7a23279717f7d0b6ee841514fbe1) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` [`726772c`](https://github.com/es-shims/RegExp.prototype.flags/commit/726772c054a499ab7680823c4bd8fa9b048d9420) +- [New] add support for `dotAll` regex flag. [`fcbd64f`](https://github.com/es-shims/RegExp.prototype.flags/commit/fcbd64f84fd974d98384bdb093bf25656eb72e8f) +- [Dev Deps] update `eslint`, `jscs`, `nsp`, `tape`, `@ljharb/eslint-config`, `@es-shims/api` [`0272934`](https://github.com/es-shims/RegExp.prototype.flags/commit/02729344addadc105b9c5e12d90cca85a75d16d6) +- [Dev Deps] update `jscs`, `nsp`, `eslint` [`e4cd264`](https://github.com/es-shims/RegExp.prototype.flags/commit/e4cd264f4afa33ff865325b04791de95696e3ae4) +- [Dev Deps] update `jscs`, `nsp`, `eslint`, `@es-shims/api` [`baf5169`](https://github.com/es-shims/RegExp.prototype.flags/commit/baf51698ac00b31b6a4a6d5646a183a409ad1118) +- [Dev Deps] update `tape`, `nsp`, `eslint`, `@ljharb/eslint-config` [`97cea15`](https://github.com/es-shims/RegExp.prototype.flags/commit/97cea152c20bb0e63e9c5111780f7b4af5d1a0e8) +- [Dev Deps] update `tape`, `discs`, `eslint`, `@ljharb/eslint-config` [`b6872f4`](https://github.com/es-shims/RegExp.prototype.flags/commit/b6872f44c833f6f7faf63881657208b6cd43ef49) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` [`14702cc`](https://github.com/es-shims/RegExp.prototype.flags/commit/14702ccd050029d4e6ea2e59d0912e6bfc16ffc0) +- [Dev Deps] update `jscs`, `@es-shims/api` [`cd060a6`](https://github.com/es-shims/RegExp.prototype.flags/commit/cd060a650db019be5244e1c1b77a29f6d79c89db) +- [Tests] up to `node` `v6.2`, `v5.11` [`14638bd`](https://github.com/es-shims/RegExp.prototype.flags/commit/14638bdbd62d6b6a7c89efb8ec57a7815032b4bb) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`b0a5ffb`](https://github.com/es-shims/RegExp.prototype.flags/commit/b0a5ffb25a76783053652e0d7f835e354f9b29b6) +- [Tests] npm run silently [`35804d4`](https://github.com/es-shims/RegExp.prototype.flags/commit/35804d45dd7f57faab923aaab914e6390813e700) +- [Tests] up to `node` `v5.9`, `v4.4` [`e0fe80d`](https://github.com/es-shims/RegExp.prototype.flags/commit/e0fe80d96783820444d6dea1e6b5739032a50c1b) +- [Tests] up to `node` `v5.7`, `v4.3` [`9739c42`](https://github.com/es-shims/RegExp.prototype.flags/commit/9739c422523571cc439d73a9ecaf5dc2e2643bec) +- [Dev Deps] update `jscs` [`4aa1699`](https://github.com/es-shims/RegExp.prototype.flags/commit/4aa1699a0582b7739f14c6cd8d5ae1a4515bd604) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `@ljharb/eslint-config` [`8bc5e6b`](https://github.com/es-shims/RegExp.prototype.flags/commit/8bc5e6ba5befc8f399e00f3c2d064519457fb57c) +- [Tests] fix npm upgrades on older nodes [`ae00bb9`](https://github.com/es-shims/RegExp.prototype.flags/commit/ae00bb9d979605f41fc598156b5c590923ac8184) +- Only apps should have lockfiles. [`6d14965`](https://github.com/es-shims/RegExp.prototype.flags/commit/6d1496550a962ea8525fb7b62dc4ac99d9513a6d) +- [Tests] use pretest/posttest for better organization [`0520cfd`](https://github.com/es-shims/RegExp.prototype.flags/commit/0520cfda23835fb5bff038a6e5cc530b0ce66985) +- [Tests] up to `node` `v5.5` [`810f62b`](https://github.com/es-shims/RegExp.prototype.flags/commit/810f62b6d2418e843b7c2c225841e9305dbc01ee) +- [Tests] on `node` `v5.3` [`f839662`](https://github.com/es-shims/RegExp.prototype.flags/commit/f839662887cbb1a5e472a9302185355b431c85c1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`78ecaa5`](https://github.com/es-shims/RegExp.prototype.flags/commit/78ecaa5b203a07f76505824f77ce1e5d60d8b0ca) +- [Tests] up to `node` `v5.2` [`c04d762`](https://github.com/es-shims/RegExp.prototype.flags/commit/c04d762a8c09ab544df14c14521f32dac3f67823) +- [Tests] up to `node` `v5.0` [`7c0d5b9`](https://github.com/es-shims/RegExp.prototype.flags/commit/7c0d5b944d9ba30f38227d0750109d582be254e2) +- [Tests] on `node` `v5.10` [`40ddafd`](https://github.com/es-shims/RegExp.prototype.flags/commit/40ddafd83e2e1c959ee8ba24cb296559f2545a0c) +- [Deps] update `define-properties` [`98ea89d`](https://github.com/es-shims/RegExp.prototype.flags/commit/98ea89dc9c41b81b84d4071105048687dab0660e) + +## [v1.1.1](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.1.0...v1.1.1) - 2015-08-16 + +### Commits + +- [Fix] cover the case where there is no descriptor on the prototype [`67014c3`](https://github.com/es-shims/RegExp.prototype.flags/commit/67014c35a93c76e28c4ab5cd3e5a54f7f40c2ddf) + +## [v1.1.0](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.0.1...v1.1.0) - 2015-08-16 + +### Commits + +- Update `jscs`, `eslint`; use my personal shared `eslint` config. [`37ca379`](https://github.com/es-shims/RegExp.prototype.flags/commit/37ca379bc72620fa6785b0a9ca791b160328c236) +- Update `eslint`, `tape`, `editorconfig-tools`, `nsp` [`cb92d6e`](https://github.com/es-shims/RegExp.prototype.flags/commit/cb92d6e8a8c1df5f00a226e11a78f38c6f7c3055) +- Implement the [es-shim API](es-shims/api). [`15eb821`](https://github.com/es-shims/RegExp.prototype.flags/commit/15eb821be2771e03a1341a08483513702118b45c) +- Refactoring to reduce complexity. [`aeb4785`](https://github.com/es-shims/RegExp.prototype.flags/commit/aeb47854f6b00355702104066c63f6eed38b5e81) +- Move implementation to `implementation.js` [`a698925`](https://github.com/es-shims/RegExp.prototype.flags/commit/a698925b4c1c78cd1ed4315b9deb5bb1707d5203) +- Update `eslint`, `jscs` [`277a4a1`](https://github.com/es-shims/RegExp.prototype.flags/commit/277a4a15e663eb823b63743b84645158b9bb9a43) +- Update `nsp`, `eslint` [`c9f3866`](https://github.com/es-shims/RegExp.prototype.flags/commit/c9f3866e25b52050f6bfe3fd0de8849de0271ea4) +- Update `tape`, `eslint` [`a08795b`](https://github.com/es-shims/RegExp.prototype.flags/commit/a08795b688b186fa5a2ec207358d81c16a07d30d) +- Make some things a bit more robust. [`450abb4`](https://github.com/es-shims/RegExp.prototype.flags/commit/450abb48974f10bfd2d9478e7ea1b9d87f004fb9) +- Update `eslint` [`25d898f`](https://github.com/es-shims/RegExp.prototype.flags/commit/25d898f62719b26fea5f9245be141103d4ec58cd) +- Test on latest two `io.js` versions. [`2e17ca3`](https://github.com/es-shims/RegExp.prototype.flags/commit/2e17ca304e12fb5071a091706a4d559b3eac968a) +- All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. [`4a2a548`](https://github.com/es-shims/RegExp.prototype.flags/commit/4a2a5480c50f30814000684462a8a3b44c87ae2e) +- Update `eslint` [`64df4e0`](https://github.com/es-shims/RegExp.prototype.flags/commit/64df4e0a2d0e2901b57652e30913db797dc0829b) +- Update `eslint` [`ac05ae5`](https://github.com/es-shims/RegExp.prototype.flags/commit/ac05ae509a4a70d107820a749ea6f02784fc41eb) +- Clean up `supportsDescriptors` check. [`e44d0de`](https://github.com/es-shims/RegExp.prototype.flags/commit/e44d0dec9c8415ff9a911b8806e1d245d6919a11) +- [Dev Deps] Update `jscs` [`8741758`](https://github.com/es-shims/RegExp.prototype.flags/commit/87417588f52f1176fc37d7c32221aa85f749aa34) +- Update `tape`, `jscs`, `nsp`, `eslint` [`db1f658`](https://github.com/es-shims/RegExp.prototype.flags/commit/db1f6584b18cc035ef3b5aec556f54e0ee8c639d) +- Test on `io.js` `v2.3` [`18c948f`](https://github.com/es-shims/RegExp.prototype.flags/commit/18c948f033c87ab2657a0395052cbec531c40900) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`c37e79f`](https://github.com/es-shims/RegExp.prototype.flags/commit/c37e79f380d87a226a6cdaa5f09f832f5dc21b7d) +- Update `tape`, `jscs`, `eslint` [`4b652bf`](https://github.com/es-shims/RegExp.prototype.flags/commit/4b652bf5f2f0e36a15227d0b4048de91ee6c4433) +- [Dev Deps] Update `tape`, `eslint` [`29d4ac0`](https://github.com/es-shims/RegExp.prototype.flags/commit/29d4ac0bea16c6a9f611cb15baccd30449f30a91) +- Test up to `io.js` `v2.1` [`9f9e342`](https://github.com/es-shims/RegExp.prototype.flags/commit/9f9e34295ced1b288dea08e0a66dffd2bc03ff8b) +- Update `covert`, `jscs` [`c98f3b4`](https://github.com/es-shims/RegExp.prototype.flags/commit/c98f3b47f01f317e8a589486dfaee482c66b8b64) +- Update `jscs` [`9e5e220`](https://github.com/es-shims/RegExp.prototype.flags/commit/9e5e220be6ec5d5b9b658235287e35bded580b06) +- [Dev Deps] update `tape` [`cdd3af2`](https://github.com/es-shims/RegExp.prototype.flags/commit/cdd3af21507b01aa524f8b87f158dfc8a8153c85) +- [Dev Deps] update `tape` [`d42d0bf`](https://github.com/es-shims/RegExp.prototype.flags/commit/d42d0bf28f8da2cb47fff49283a07a693f8cb626) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`a5e7453`](https://github.com/es-shims/RegExp.prototype.flags/commit/a5e745375c01e9f90ff632c55a5b44b6ada38217) +- Update `tape` [`2a675ec`](https://github.com/es-shims/RegExp.prototype.flags/commit/2a675ec707a9d89aea403d0b9a723ea531e50c2d) +- Test on `io.js` `v2.5` [`448cbdb`](https://github.com/es-shims/RegExp.prototype.flags/commit/448cbdb7df47e52677daea4e0c41e892ad8770e4) +- Test on `io.js` `v2.4` [`948e511`](https://github.com/es-shims/RegExp.prototype.flags/commit/948e51129c01147ffe4dedc3a7d4980128d0cf73) +- Test on `io.js` `v2.2` [`4793278`](https://github.com/es-shims/RegExp.prototype.flags/commit/4793278f5aca187e36b42b08fc1388d8021400e2) +- Update `eslint` [`0f463da`](https://github.com/es-shims/RegExp.prototype.flags/commit/0f463daa14a193ed94b16c46832074d63e861c91) +- Update `eslint` [`5a16967`](https://github.com/es-shims/RegExp.prototype.flags/commit/5a16967db71bb8a24c81a27ee366f0b02b663e34) +- Test on `io.js` `v3.0` [`7ba8706`](https://github.com/es-shims/RegExp.prototype.flags/commit/7ba87064bc8520d34a9560bea8e366d70c93dbbb) +- Test on `iojs-v1.2` [`b521e09`](https://github.com/es-shims/RegExp.prototype.flags/commit/b521e099b7de48cfbdd6860265eb5e972d2859a5) + +## [v1.0.1](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.0.0...v1.0.1) - 2014-12-13 + +### Merged + +- Match the spec properly: throw when not an object; make getter generic. [`#3`](https://github.com/es-shims/RegExp.prototype.flags/pull/3) + +### Fixed + +- Match the spec properly [`#1`](https://github.com/es-shims/RegExp.prototype.flags/issues/1) + +### Commits + +- Speed up the “is object” check in case of `null` or `undefined` [`77137f9`](https://github.com/es-shims/RegExp.prototype.flags/commit/77137f99449c9b6583cdfda295a00b832dfd45f3) + +## v1.0.0 - 2014-12-10 + +### Commits + +- Adding dotfiles [`313812e`](https://github.com/es-shims/RegExp.prototype.flags/commit/313812e1d8ff42a13dbc8689f2e719324c46c9ca) +- Tests [`625a042`](https://github.com/es-shims/RegExp.prototype.flags/commit/625a042220a3152b49608fb6f187f67bff02b6fb) +- Add package.json [`8b98257`](https://github.com/es-shims/RegExp.prototype.flags/commit/8b98257f900d0a73c8eb3805b9b01999e05e880a) +- Adding the README [`884798b`](https://github.com/es-shims/RegExp.prototype.flags/commit/884798b710d5a85bc6d9a6879f509766e2e57c0e) +- Implementation. [`4186cc9`](https://github.com/es-shims/RegExp.prototype.flags/commit/4186cc9d9a7533f78d88be976f0a8a2757604fc5) +- Adding LICENSE and CHANGELOG [`f87fa81`](https://github.com/es-shims/RegExp.prototype.flags/commit/f87fa8126cc6c39747fbe0dc6cb40ca0ff77fbbc) +- Fixing README URLs [`b821703`](https://github.com/es-shims/RegExp.prototype.flags/commit/b821703d5e5b01ee4f526f15c8e525645cf95ef7) +- Clean up dependencies; update `tape`, `jscs`, `nsp` [`0e13fc1`](https://github.com/es-shims/RegExp.prototype.flags/commit/0e13fc12df09f3a7ac30116ef13bba820c220730) +- Initial commit. [`8a9e35e`](https://github.com/es-shims/RegExp.prototype.flags/commit/8a9e35e15f65c9640e64ee14fab190a60993efaa) diff --git a/node_modules/regexp.prototype.flags/LICENSE b/node_modules/regexp.prototype.flags/LICENSE new file mode 100644 index 0000000..e5956a8 --- /dev/null +++ b/node_modules/regexp.prototype.flags/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (C) 2014 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/regexp.prototype.flags/README.md b/node_modules/regexp.prototype.flags/README.md new file mode 100644 index 0000000..77e151e --- /dev/null +++ b/node_modules/regexp.prototype.flags/README.md @@ -0,0 +1,54 @@ +RegExp.prototype.flags [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-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] + +[![browser support][testling-svg]][testling-url] + +An ES6 spec-compliant `RegExp.prototype.flags` shim. Invoke its "shim" method to shim RegExp.prototype.flags if it is unavailable. +*Note*: `RegExp#flags` requires a true ES5 environment - specifically, one with ES5 getters. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES5-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-get-regexp.prototype.flags). + +Most common usage: +```js +var flags = require('regexp.prototype.flags'); + +assert(flags(/a/) === ''); +assert(flags(new RegExp('a') === ''); +assert(flags(/a/mig) === 'gim'); +assert(flags(new RegExp('a', 'mig')) === 'gim'); + +if (!RegExp.prototype.flags) { + flags.shim(); +} + +assert(flags(/a/) === /a/.flags); +assert(flags(new RegExp('a') === new RegExp('a').flags); +assert(flags(/a/mig) === /a/mig.flags); +assert(flags(new RegExp('a', 'mig')) === new RegExp('a', 'mig').flags); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/regexp.prototype.flags +[npm-version-svg]: http://versionbadg.es/es-shims/RegExp.prototype.flags.svg +[travis-svg]: https://travis-ci.org/es-shims/RegExp.prototype.flags.svg +[travis-url]: https://travis-ci.org/es-shims/RegExp.prototype.flags +[deps-svg]: https://david-dm.org/es-shims/RegExp.prototype.flags.svg +[deps-url]: https://david-dm.org/es-shims/RegExp.prototype.flags +[dev-deps-svg]: https://david-dm.org/es-shims/RegExp.prototype.flags/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/RegExp.prototype.flags#info=devDependencies +[testling-svg]: https://ci.testling.com/es-shims/RegExp.prototype.flags.png +[testling-url]: https://ci.testling.com/es-shims/RegExp.prototype.flags +[npm-badge-png]: https://nodei.co/npm/regexp.prototype.flags.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/regexp.prototype.flags.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/regexp.prototype.flags.svg +[downloads-url]: http://npm-stat.com/charts.html?package=regexp.prototype.flags diff --git a/node_modules/regexp.prototype.flags/auto.js b/node_modules/regexp.prototype.flags/auto.js new file mode 100644 index 0000000..8ebf606 --- /dev/null +++ b/node_modules/regexp.prototype.flags/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/regexp.prototype.flags/implementation.js b/node_modules/regexp.prototype.flags/implementation.js new file mode 100644 index 0000000..9d2f0bc --- /dev/null +++ b/node_modules/regexp.prototype.flags/implementation.js @@ -0,0 +1,39 @@ +'use strict'; + +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); + +var $Object = Object; +var $TypeError = TypeError; + +module.exports = function flags() { + if (this != null && this !== $Object(this)) { + throw new $TypeError('RegExp.prototype.flags getter called on non-object'); + } + var result = ''; + if (this.hasIndices) { + result += 'd'; + } + if (this.global) { + result += 'g'; + } + if (this.ignoreCase) { + result += 'i'; + } + if (this.multiline) { + result += 'm'; + } + if (this.dotAll) { + result += 's'; + } + if (this.unicode) { + result += 'u'; + } + if (this.sticky) { + result += 'y'; + } + return result; +}; + +if (functionsHaveConfigurableNames && Object.defineProperty) { + Object.defineProperty(module.exports, 'name', { value: 'get flags' }); +} diff --git a/node_modules/regexp.prototype.flags/index.js b/node_modules/regexp.prototype.flags/index.js new file mode 100644 index 0000000..d6054c7 --- /dev/null +++ b/node_modules/regexp.prototype.flags/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var define = require('define-properties'); +var callBind = require('call-bind'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var flagsBound = callBind(getPolyfill()); + +define(flagsBound, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = flagsBound; diff --git a/node_modules/regexp.prototype.flags/package.json b/node_modules/regexp.prototype.flags/package.json new file mode 100644 index 0000000..cc8f120 --- /dev/null +++ b/node_modules/regexp.prototype.flags/package.json @@ -0,0 +1,92 @@ +{ + "name": "regexp.prototype.flags", + "version": "1.4.3", + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "ES6 spec-compliant RegExp.prototype.flags shim.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "es-shim-api --bound", + "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/es-shims/RegExp.prototype.flags.git" + }, + "keywords": [ + "RegExp.prototype.flags", + "regex", + "regular expression", + "ES6", + "shim", + "flag", + "flags", + "regexp", + "RegExp#flags", + "polyfill", + "es-shim API" + ], + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "functions-have-names": "^1.2.2" + }, + "devDependencies": { + "@es-shims/api": "^2.2.3", + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "available-regexp-flags": "^1.0.0", + "covert": "^1.1.1", + "eclint": "^2.8.1", + "eslint": "=8.8.0", + "foreach": "^2.0.5", + "has": "^1.0.3", + "has-strict-mode": "^1.0.1", + "nyc": "^10.3.2", + "object-inspect": "^1.12.0", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.3" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/9.0..latest", + "firefox/4.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/11.6..latest", + "opera/next", + "safari/5.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 + } +} diff --git a/node_modules/regexp.prototype.flags/polyfill.js b/node_modules/regexp.prototype.flags/polyfill.js new file mode 100644 index 0000000..2ea3dac --- /dev/null +++ b/node_modules/regexp.prototype.flags/polyfill.js @@ -0,0 +1,36 @@ +'use strict'; + +var implementation = require('./implementation'); + +var supportsDescriptors = require('define-properties').supportsDescriptors; +var $gOPD = Object.getOwnPropertyDescriptor; + +module.exports = function getPolyfill() { + if (supportsDescriptors && (/a/mig).flags === 'gim') { + var descriptor = $gOPD(RegExp.prototype, 'flags'); + if ( + descriptor + && typeof descriptor.get === 'function' + && typeof RegExp.prototype.dotAll === 'boolean' + && typeof RegExp.prototype.hasIndices === 'boolean' + ) { + /* eslint getter-return: 0 */ + var calls = ''; + var o = {}; + Object.defineProperty(o, 'hasIndices', { + get: function () { + calls += 'd'; + } + }); + Object.defineProperty(o, 'sticky', { + get: function () { + calls += 'y'; + } + }); + if (calls === 'dy') { + return descriptor.get; + } + } + } + return implementation; +}; diff --git a/node_modules/regexp.prototype.flags/shim.js b/node_modules/regexp.prototype.flags/shim.js new file mode 100644 index 0000000..3ec77c1 --- /dev/null +++ b/node_modules/regexp.prototype.flags/shim.js @@ -0,0 +1,26 @@ +'use strict'; + +var supportsDescriptors = require('define-properties').supportsDescriptors; +var getPolyfill = require('./polyfill'); +var gOPD = Object.getOwnPropertyDescriptor; +var defineProperty = Object.defineProperty; +var TypeErr = TypeError; +var getProto = Object.getPrototypeOf; +var regex = /a/; + +module.exports = function shimFlags() { + if (!supportsDescriptors || !getProto) { + throw new TypeErr('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors'); + } + var polyfill = getPolyfill(); + var proto = getProto(regex); + var descriptor = gOPD(proto, 'flags'); + if (!descriptor || descriptor.get !== polyfill) { + defineProperty(proto, 'flags', { + configurable: true, + enumerable: false, + get: polyfill + }); + } + return polyfill; +}; diff --git a/node_modules/regexp.prototype.flags/test/implementation.js b/node_modules/regexp.prototype.flags/test/implementation.js new file mode 100644 index 0000000..1e3a714 --- /dev/null +++ b/node_modules/regexp.prototype.flags/test/implementation.js @@ -0,0 +1,20 @@ +'use strict'; + +var flags = require('../implementation'); +var callBind = require('call-bind'); +var test = require('tape'); +var hasStrictMode = require('has-strict-mode')(); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', { skip: !hasStrictMode }, function (st) { + /* eslint no-useless-call: 0 */ + st['throws'](function () { flags.call(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { flags.call(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(flags), t); + + t.end(); +}); diff --git a/node_modules/regexp.prototype.flags/test/index.js b/node_modules/regexp.prototype.flags/test/index.js new file mode 100644 index 0000000..10d1071 --- /dev/null +++ b/node_modules/regexp.prototype.flags/test/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var flags = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { flags(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { flags(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(flags, t); + + t.end(); +}); diff --git a/node_modules/regexp.prototype.flags/test/shimmed.js b/node_modules/regexp.prototype.flags/test/shimmed.js new file mode 100644 index 0000000..059e0e1 --- /dev/null +++ b/node_modules/regexp.prototype.flags/test/shimmed.js @@ -0,0 +1,48 @@ +'use strict'; + +require('../auto'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); + +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); +var hasStrictMode = require('has-strict-mode')(); + +var runTests = require('./tests'); + +test('shimmed', function (t) { + var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, 'flags'); + + t.equal(descriptor.get.length, 0, 'RegExp#flags getter has a length of 0'); + + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(descriptor.get.name, functionsHaveConfigurableNames ? 'get flags' : 'flags', 'RegExp#flags getter has name "get flags" (or "flags" if function names are not configurable)'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(RegExp.prototype, 'flags'), 'RegExp#flags is not enumerable'); + et.end(); + }); + + t.test('bad array/this value', { skip: !hasStrictMode }, function (st) { + st['throws'](function () { return descriptor.get.call(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return descriptor.get.call(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + t.test('has the correct descriptor', function (st) { + st.equal(descriptor.configurable, true); + st.equal(descriptor.enumerable, false); + st.equal(typeof descriptor.get, 'function'); + st.equal(descriptor.set, undefined); + st.end(); + }); + + runTests(callBind(descriptor.get), t); + + t.end(); +}); diff --git a/node_modules/regexp.prototype.flags/test/tests.js b/node_modules/regexp.prototype.flags/test/tests.js new file mode 100644 index 0000000..0421a99 --- /dev/null +++ b/node_modules/regexp.prototype.flags/test/tests.js @@ -0,0 +1,141 @@ +'use strict'; + +var has = require('has'); +var inspect = require('object-inspect'); +var supportsDescriptors = require('define-properties').supportsDescriptors; + +var forEach = require('foreach'); +var availableFlags = require('available-regexp-flags'); +var regexProperties = require('available-regexp-flags/properties'); + +var sortedFlags = availableFlags.slice().sort(function (a, b) { return a.localeCompare(b); }).join(''); + +var getRegexLiteral = function (stringRegex) { + try { + // eslint-disable-next-line no-new-func + return Function('return ' + stringRegex + ';')(); + } catch (e) { /**/ } + return null; +}; + +module.exports = function runTests(flags, t) { + t.equal(flags(/a/g), 'g', 'flags(/a/g) !== "g"'); + t.equal(flags(/a/gmi), 'gim', 'flags(/a/gmi) !== "gim"'); + t.equal(flags(new RegExp('a', 'gmi')), 'gim', 'flags(new RegExp("a", "gmi")) !== "gim"'); + t.equal(flags(/a/), '', 'flags(/a/) !== ""'); + t.equal(flags(new RegExp('a')), '', 'flags(new RegExp("a")) !== ""'); + + forEach(availableFlags, function (flag) { + var property = regexProperties[flag]; + t.test(property + ' flag', function (st) { + st.equal(flags(getRegexLiteral('/a/' + flag)), flag, 'flags(/a/' + flag + ') !== ' + inspect(flag)); + st.equal(flags(new RegExp('a', flag)), flag, 'flags(new RegExp("a", ' + inspect(flag) + ')) !== ' + inspect(flag)); + st.end(); + }); + }); + + t.test('sorting', function (st) { + st.equal(flags(/a/gim), 'gim', 'flags(/a/gim) !== "gim"'); + st.equal(flags(/a/mig), 'gim', 'flags(/a/mig) !== "gim"'); + st.equal(flags(/a/mgi), 'gim', 'flags(/a/mgi) !== "gim"'); + if (has(RegExp.prototype, 'sticky')) { + st.equal(flags(getRegexLiteral('/a/gyim')), 'gimy', 'flags(/a/gyim) !== "gimy"'); + } + if (has(RegExp.prototype, 'unicode')) { + st.equal(flags(getRegexLiteral('/a/ugmi')), 'gimu', 'flags(/a/ugmi) !== "gimu"'); + } + if (has(RegExp.prototype, 'dotAll')) { + st.equal(flags(getRegexLiteral('/a/sgmi')), 'gims', 'flags(/a/sgmi) !== "gims"'); + } + + var randomFlags = availableFlags.slice().sort(function () { return Math.random() > 0.5 ? 1 : -1; }).join(''); + st.equal( + flags(getRegexLiteral('/a/' + randomFlags)), + sortedFlags, + 'random: flags(/a/' + randomFlags + ') === ' + inspect(sortedFlags) + ); + + st.end(); + }); + + t.test('basic examples', function (st) { + st.equal(flags(/a/g), 'g', '(/a/g).flags !== "g"'); + st.equal(flags(/a/gmi), 'gim', '(/a/gmi).flags !== "gim"'); + st.equal(flags(new RegExp('a', 'gmi')), 'gim', 'new RegExp("a", "gmi").flags !== "gim"'); + st.equal(flags(/a/), '', '(/a/).flags !== ""'); + st.equal(flags(new RegExp('a')), '', 'new RegExp("a").flags !== ""'); + + st.end(); + }); + + t.test('generic flags', function (st) { + st.equal(flags({}), ''); + st.equal(flags({ ignoreCase: true }), 'i'); + st.equal(flags({ dotAll: 1, global: 0, sticky: 1, unicode: 1 }), 'suy'); + st.equal(flags({ __proto__: { multiline: true } }), 'm'); + + var obj = {}; + forEach(availableFlags, function (flag) { + obj[regexProperties[flag]] = true; + }); + st.equal(flags(obj), sortedFlags, 'an object with every available flag: ' + sortedFlags); + + st.end(); + }); + + t.test('throws properly', function (st) { + var nonObjects = ['', false, true, 42, NaN, null, undefined]; + st.plan(nonObjects.length); + var throwsOnNonObject = function (nonObject) { + st['throws'](flags.bind(null, nonObject), TypeError, inspect(nonObject) + ' is not an Object'); + }; + nonObjects.forEach(throwsOnNonObject); + }); + + t.test('getters', { skip: !supportsDescriptors }, function (st) { + /* eslint getter-return: 0 */ + var calls = ''; + var re = {}; + Object.defineProperty(re, 'hasIndices', { + get: function () { + calls += 'd'; + } + }); + Object.defineProperty(re, 'global', { + get: function () { + calls += 'g'; + } + }); + Object.defineProperty(re, 'ignoreCase', { + get: function () { + calls += 'i'; + } + }); + Object.defineProperty(re, 'multiline', { + get: function () { + calls += 'm'; + } + }); + Object.defineProperty(re, 'dotAll', { + get: function () { + calls += 's'; + } + }); + Object.defineProperty(re, 'unicode', { + get: function () { + calls += 'u'; + } + }); + Object.defineProperty(re, 'sticky', { + get: function () { + calls += 'y'; + } + }); + + flags(re); + + st.equal(calls, 'dgimsuy', 'getters are called in expected order'); + + st.end(); + }); +}; diff --git a/node_modules/resolve/.editorconfig b/node_modules/resolve/.editorconfig new file mode 100644 index 0000000..d63f0bb --- /dev/null +++ b/node_modules/resolve/.editorconfig @@ -0,0 +1,37 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 200 + +[*.js] +block_comment_start = /* +block_comment = * +block_comment_end = */ + +[*.yml] +indent_size = 1 + +[package.json] +indent_style = tab + +[lib/core.json] +indent_style = tab + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[{*.json,Makefile}] +max_line_length = off + +[test/{dotdot,resolver,module_dir,multirepo,node_path,pathfilter,precedence}/**/*] +indent_style = off +indent_size = off +max_line_length = off +insert_final_newline = off diff --git a/node_modules/resolve/.eslintrc b/node_modules/resolve/.eslintrc new file mode 100644 index 0000000..ce1be6e --- /dev/null +++ b/node_modules/resolve/.eslintrc @@ -0,0 +1,65 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "indent": [2, 4], + "strict": 0, + "complexity": 0, + "consistent-return": 0, + "curly": 0, + "dot-notation": [2, { "allowKeywords": true }], + "func-name-matching": 0, + "func-style": 0, + "global-require": 1, + "id-length": [2, { "min": 1, "max": 30 }], + "max-lines": [2, 350], + "max-lines-per-function": 0, + "max-nested-callbacks": 0, + "max-params": 0, + "max-statements-per-line": [2, { "max": 2 }], + "max-statements": 0, + "no-magic-numbers": 0, + "no-shadow": 0, + "no-use-before-define": 0, + "sort-keys": 0, + }, + "overrides": [ + { + "files": "bin/**", + "rules": { + "no-process-exit": "off", + }, + }, + { + "files": "example/**", + "rules": { + "no-console": 0, + }, + }, + { + "files": "test/resolver/nested_symlinks/mylib/*.js", + "rules": { + "no-throw-literal": 0, + }, + }, + { + "files": "test/**", + "parserOptions": { + "ecmaVersion": 5, + "allowReserved": false, + }, + "rules": { + "dot-notation": [2, { "allowPattern": "throws" }], + "max-lines": 0, + "max-lines-per-function": 0, + "no-unused-vars": [2, { "vars": "all", "args": "none" }], + }, + }, + ], + + "ignorePatterns": [ + "./test/resolver/malformed_package_json/package.json", + ], +} diff --git a/node_modules/resolve/.github/FUNDING.yml b/node_modules/resolve/.github/FUNDING.yml new file mode 100644 index 0000000..d9c0595 --- /dev/null +++ b/node_modules/resolve/.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/resolve +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/resolve/LICENSE b/node_modules/resolve/LICENSE new file mode 100644 index 0000000..ff4fce2 --- /dev/null +++ b/node_modules/resolve/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012 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/resolve/SECURITY.md b/node_modules/resolve/SECURITY.md new file mode 100644 index 0000000..82e4285 --- /dev/null +++ b/node_modules/resolve/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/resolve/async.js b/node_modules/resolve/async.js new file mode 100644 index 0000000..f38c581 --- /dev/null +++ b/node_modules/resolve/async.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/async'); diff --git a/node_modules/resolve/bin/resolve b/node_modules/resolve/bin/resolve new file mode 100755 index 0000000..5ee329a --- /dev/null +++ b/node_modules/resolve/bin/resolve @@ -0,0 +1,50 @@ +#!/usr/bin/env node + +'use strict'; + +var path = require('path'); +var fs = require('fs'); + +if ( + String(process.env.npm_lifecycle_script).slice(0, 8) !== 'resolve ' + && ( + !process.argv + || process.argv.length < 2 + || (process.argv[1] !== __filename && fs.statSync(process.argv[1]).ino !== fs.statSync(__filename).ino) + || (process.env._ && path.resolve(process.env._) !== __filename) + ) +) { + console.error('Error: `resolve` must be run directly as an executable'); + process.exit(1); +} + +var supportsPreserveSymlinkFlag = require('supports-preserve-symlinks-flag'); + +var preserveSymlinks = false; +for (var i = 2; i < process.argv.length; i += 1) { + if (process.argv[i].slice(0, 2) === '--') { + if (supportsPreserveSymlinkFlag && process.argv[i] === '--preserve-symlinks') { + preserveSymlinks = true; + } else if (process.argv[i].length > 2) { + console.error('Unknown argument ' + process.argv[i].replace(/[=].*$/, '')); + process.exit(2); + } + process.argv.splice(i, 1); + i -= 1; + if (process.argv[i] === '--') { break; } // eslint-disable-line no-restricted-syntax + } +} + +if (process.argv.length < 3) { + console.error('Error: `resolve` expects a specifier'); + process.exit(2); +} + +var resolve = require('../'); + +var result = resolve.sync(process.argv[2], { + basedir: process.cwd(), + preserveSymlinks: preserveSymlinks +}); + +console.log(result); diff --git a/node_modules/resolve/example/async.js b/node_modules/resolve/example/async.js new file mode 100644 index 0000000..20e65dc --- /dev/null +++ b/node_modules/resolve/example/async.js @@ -0,0 +1,5 @@ +var resolve = require('../'); +resolve('tap', { basedir: __dirname }, function (err, res) { + if (err) console.error(err); + else console.log(res); +}); diff --git a/node_modules/resolve/example/sync.js b/node_modules/resolve/example/sync.js new file mode 100644 index 0000000..54b2cc1 --- /dev/null +++ b/node_modules/resolve/example/sync.js @@ -0,0 +1,3 @@ +var resolve = require('../'); +var res = resolve.sync('tap', { basedir: __dirname }); +console.log(res); diff --git a/node_modules/resolve/index.js b/node_modules/resolve/index.js new file mode 100644 index 0000000..125d814 --- /dev/null +++ b/node_modules/resolve/index.js @@ -0,0 +1,6 @@ +var async = require('./lib/async'); +async.core = require('./lib/core'); +async.isCore = require('./lib/is-core'); +async.sync = require('./lib/sync'); + +module.exports = async; diff --git a/node_modules/resolve/lib/async.js b/node_modules/resolve/lib/async.js new file mode 100644 index 0000000..60d2555 --- /dev/null +++ b/node_modules/resolve/lib/async.js @@ -0,0 +1,329 @@ +var fs = require('fs'); +var getHomedir = require('./homedir'); +var path = require('path'); +var caller = require('./caller'); +var nodeModulesPaths = require('./node-modules-paths'); +var normalizeOptions = require('./normalize-options'); +var isCore = require('is-core-module'); + +var realpathFS = process.platform !== 'win32' && fs.realpath && typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; + +var homedir = getHomedir(); +var defaultPaths = function () { + return [ + path.join(homedir, '.node_modules'), + path.join(homedir, '.node_libraries') + ]; +}; + +var defaultIsFile = function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultIsDir = function isDirectory(dir, cb) { + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultRealpath = function realpath(x, cb) { + realpathFS(x, function (realpathErr, realPath) { + if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr); + else cb(null, realpathErr ? x : realPath); + }); +}; + +var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { + if (opts && opts.preserveSymlinks === false) { + realpath(x, cb); + } else { + cb(null, x); + } +}; + +var defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) { + readFile(pkgfile, function (readFileErr, body) { + if (readFileErr) cb(readFileErr); + else { + try { + var pkg = JSON.parse(body); + cb(null, pkg); + } catch (jsonErr) { + cb(null); + } + } + }); +}; + +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); + } + return dirs; +}; + +module.exports = function resolve(x, options, callback) { + var cb = callback; + var opts = options; + if (typeof options === 'function') { + cb = opts; + opts = {}; + } + if (typeof x !== 'string') { + var err = new TypeError('Path must be a string.'); + return process.nextTick(function () { + cb(err); + }); + } + + opts = normalizeOptions(x, opts); + + var isFile = opts.isFile || defaultIsFile; + var isDirectory = opts.isDirectory || defaultIsDir; + var readFile = opts.readFile || fs.readFile; + var realpath = opts.realpath || defaultRealpath; + var readPackage = opts.readPackage || defaultReadPackage; + if (opts.readFile && opts.readPackage) { + var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.'); + return process.nextTick(function () { + cb(conflictErr); + }); + } + var packageIterator = opts.packageIterator; + + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; + + opts.paths = opts.paths || defaultPaths(); + + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = path.resolve(basedir); + + maybeRealpath( + realpath, + absoluteStart, + opts, + function (err, realStart) { + if (err) cb(err); + else init(realStart); + } + ); + + var res; + function init(basedir) { + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + res = path.resolve(basedir, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + if ((/\/$/).test(x) && res === basedir) { + loadAsDirectory(res, opts.package, onfile); + } else loadAsFile(res, opts.package, onfile); + } else if (includeCoreModules && isCore(x)) { + return cb(null, x); + } else loadNodeModules(x, basedir, function (err, n, pkg) { + if (err) cb(err); + else if (n) { + return maybeRealpath(realpath, n, opts, function (err, realN) { + if (err) { + cb(err); + } else { + cb(null, realN, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function onfile(err, m, pkg) { + if (err) cb(err); + else if (m) cb(null, m, pkg); + else loadAsDirectory(res, function (err, d, pkg) { + if (err) cb(err); + else if (d) { + maybeRealpath(realpath, d, opts, function (err, realD) { + if (err) { + cb(err); + } else { + cb(null, realD, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function loadAsFile(x, thePackage, callback) { + var loadAsFilePackage = thePackage; + var cb = callback; + if (typeof loadAsFilePackage === 'function') { + cb = loadAsFilePackage; + loadAsFilePackage = undefined; + } + + var exts = [''].concat(extensions); + load(exts, x, loadAsFilePackage); + + function load(exts, x, loadPackage) { + if (exts.length === 0) return cb(null, undefined, loadPackage); + var file = x + exts[0]; + + var pkg = loadPackage; + if (pkg) onpkg(null, pkg); + else loadpkg(path.dirname(file), onpkg); + + function onpkg(err, pkg_, dir) { + pkg = pkg_; + if (err) return cb(err); + if (dir && pkg && opts.pathFilter) { + var rfile = path.relative(dir, file); + var rel = rfile.slice(0, rfile.length - exts[0].length); + var r = opts.pathFilter(pkg, x, rel); + if (r) return load( + [''].concat(extensions.slice()), + path.resolve(dir, r), + pkg + ); + } + isFile(file, onex); + } + function onex(err, ex) { + if (err) return cb(err); + if (ex) return cb(null, file, pkg); + load(exts.slice(1), x, pkg); + } + } + } + + function loadpkg(dir, cb) { + if (dir === '' || dir === '/') return cb(null); + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return cb(null); + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); + + maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return loadpkg(path.dirname(dir), cb); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + // on err, ex is false + if (!ex) return loadpkg(path.dirname(dir), cb); + + readPackage(readFile, pkgfile, function (err, pkgParam) { + if (err) cb(err); + + var pkg = pkgParam; + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + cb(null, pkg, dir); + }); + }); + }); + } + + function loadAsDirectory(x, loadAsDirectoryPackage, callback) { + var cb = callback; + var fpkg = loadAsDirectoryPackage; + if (typeof fpkg === 'function') { + cb = fpkg; + fpkg = opts.package; + } + + maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return cb(unwrapErr); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + if (err) return cb(err); + if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); + + readPackage(readFile, pkgfile, function (err, pkgParam) { + if (err) return cb(err); + + var pkg = pkgParam; + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + return cb(mainError); + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); + + var dir = path.resolve(x, pkg.main); + loadAsDirectory(dir, pkg, function (err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + loadAsFile(path.join(x, 'index'), pkg, cb); + }); + }); + return; + } + + loadAsFile(path.join(x, '/index'), pkg, cb); + }); + }); + }); + } + + function processDirs(cb, dirs) { + if (dirs.length === 0) return cb(null, undefined); + var dir = dirs[0]; + + isDirectory(path.dirname(dir), isdir); + + function isdir(err, isdir) { + if (err) return cb(err); + if (!isdir) return processDirs(cb, dirs.slice(1)); + loadAsFile(dir, opts.package, onfile); + } + + function onfile(err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + loadAsDirectory(dir, opts.package, ondir); + } + + function ondir(err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + processDirs(cb, dirs.slice(1)); + } + } + function loadNodeModules(x, start, cb) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + processDirs( + cb, + packageIterator ? packageIterator(x, start, thunk, opts) : thunk() + ); + } +}; diff --git a/node_modules/resolve/lib/caller.js b/node_modules/resolve/lib/caller.js new file mode 100644 index 0000000..b14a280 --- /dev/null +++ b/node_modules/resolve/lib/caller.js @@ -0,0 +1,8 @@ +module.exports = function () { + // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + var origPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = (new Error()).stack; + Error.prepareStackTrace = origPrepareStackTrace; + return stack[2].getFileName(); +}; diff --git a/node_modules/resolve/lib/core.js b/node_modules/resolve/lib/core.js new file mode 100644 index 0000000..ecc5b2e --- /dev/null +++ b/node_modules/resolve/lib/core.js @@ -0,0 +1,52 @@ +var current = (process.versions && process.versions.node && process.versions.node.split('.')) || []; + +function specifierIncluded(specifier) { + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + + for (var i = 0; i < 3; ++i) { + var cur = parseInt(current[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } else if (op === '>=') { + return cur >= ver; + } + return false; + } + return op === '>='; +} + +function matchesRange(range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { return false; } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(specifiers[i])) { return false; } + } + return true; +} + +function versionIncluded(specifierValue) { + if (typeof specifierValue === 'boolean') { return specifierValue; } + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(specifierValue[i])) { return true; } + } + return false; + } + return matchesRange(specifierValue); +} + +var data = require('./core.json'); + +var core = {}; +for (var mod in data) { // eslint-disable-line no-restricted-syntax + if (Object.prototype.hasOwnProperty.call(data, mod)) { + core[mod] = versionIncluded(data[mod]); + } +} +module.exports = core; diff --git a/node_modules/resolve/lib/core.json b/node_modules/resolve/lib/core.json new file mode 100644 index 0000000..058584b --- /dev/null +++ b/node_modules/resolve/lib/core.json @@ -0,0 +1,153 @@ +{ + "assert": true, + "node:assert": [">= 14.18 && < 15", ">= 16"], + "assert/strict": ">= 15", + "node:assert/strict": ">= 16", + "async_hooks": ">= 8", + "node:async_hooks": [">= 14.18 && < 15", ">= 16"], + "buffer_ieee754": ">= 0.5 && < 0.9.7", + "buffer": true, + "node:buffer": [">= 14.18 && < 15", ">= 16"], + "child_process": true, + "node:child_process": [">= 14.18 && < 15", ">= 16"], + "cluster": ">= 0.5", + "node:cluster": [">= 14.18 && < 15", ">= 16"], + "console": true, + "node:console": [">= 14.18 && < 15", ">= 16"], + "constants": true, + "node:constants": [">= 14.18 && < 15", ">= 16"], + "crypto": true, + "node:crypto": [">= 14.18 && < 15", ">= 16"], + "_debug_agent": ">= 1 && < 8", + "_debugger": "< 8", + "dgram": true, + "node:dgram": [">= 14.18 && < 15", ">= 16"], + "diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"], + "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"], + "dns": true, + "node:dns": [">= 14.18 && < 15", ">= 16"], + "dns/promises": ">= 15", + "node:dns/promises": ">= 16", + "domain": ">= 0.7.12", + "node:domain": [">= 14.18 && < 15", ">= 16"], + "events": true, + "node:events": [">= 14.18 && < 15", ">= 16"], + "freelist": "< 6", + "fs": true, + "node:fs": [">= 14.18 && < 15", ">= 16"], + "fs/promises": [">= 10 && < 10.1", ">= 14"], + "node:fs/promises": [">= 14.18 && < 15", ">= 16"], + "_http_agent": ">= 0.11.1", + "node:_http_agent": [">= 14.18 && < 15", ">= 16"], + "_http_client": ">= 0.11.1", + "node:_http_client": [">= 14.18 && < 15", ">= 16"], + "_http_common": ">= 0.11.1", + "node:_http_common": [">= 14.18 && < 15", ">= 16"], + "_http_incoming": ">= 0.11.1", + "node:_http_incoming": [">= 14.18 && < 15", ">= 16"], + "_http_outgoing": ">= 0.11.1", + "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"], + "_http_server": ">= 0.11.1", + "node:_http_server": [">= 14.18 && < 15", ">= 16"], + "http": true, + "node:http": [">= 14.18 && < 15", ">= 16"], + "http2": ">= 8.8", + "node:http2": [">= 14.18 && < 15", ">= 16"], + "https": true, + "node:https": [">= 14.18 && < 15", ">= 16"], + "inspector": ">= 8", + "node:inspector": [">= 14.18 && < 15", ">= 16"], + "_linklist": "< 8", + "module": true, + "node:module": [">= 14.18 && < 15", ">= 16"], + "net": true, + "node:net": [">= 14.18 && < 15", ">= 16"], + "node-inspect/lib/_inspect": ">= 7.6 && < 12", + "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12", + "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12", + "os": true, + "node:os": [">= 14.18 && < 15", ">= 16"], + "path": true, + "node:path": [">= 14.18 && < 15", ">= 16"], + "path/posix": ">= 15.3", + "node:path/posix": ">= 16", + "path/win32": ">= 15.3", + "node:path/win32": ">= 16", + "perf_hooks": ">= 8.5", + "node:perf_hooks": [">= 14.18 && < 15", ">= 16"], + "process": ">= 1", + "node:process": [">= 14.18 && < 15", ">= 16"], + "punycode": ">= 0.5", + "node:punycode": [">= 14.18 && < 15", ">= 16"], + "querystring": true, + "node:querystring": [">= 14.18 && < 15", ">= 16"], + "readline": true, + "node:readline": [">= 14.18 && < 15", ">= 16"], + "readline/promises": ">= 17", + "node:readline/promises": ">= 17", + "repl": true, + "node:repl": [">= 14.18 && < 15", ">= 16"], + "smalloc": ">= 0.11.5 && < 3", + "_stream_duplex": ">= 0.9.4", + "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"], + "_stream_transform": ">= 0.9.4", + "node:_stream_transform": [">= 14.18 && < 15", ">= 16"], + "_stream_wrap": ">= 1.4.1", + "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"], + "_stream_passthrough": ">= 0.9.4", + "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"], + "_stream_readable": ">= 0.9.4", + "node:_stream_readable": [">= 14.18 && < 15", ">= 16"], + "_stream_writable": ">= 0.9.4", + "node:_stream_writable": [">= 14.18 && < 15", ">= 16"], + "stream": true, + "node:stream": [">= 14.18 && < 15", ">= 16"], + "stream/consumers": ">= 16.7", + "node:stream/consumers": ">= 16.7", + "stream/promises": ">= 15", + "node:stream/promises": ">= 16", + "stream/web": ">= 16.5", + "node:stream/web": ">= 16.5", + "string_decoder": true, + "node:string_decoder": [">= 14.18 && < 15", ">= 16"], + "sys": [">= 0.4 && < 0.7", ">= 0.8"], + "node:sys": [">= 14.18 && < 15", ">= 16"], + "node:test": ">= 18", + "timers": true, + "node:timers": [">= 14.18 && < 15", ">= 16"], + "timers/promises": ">= 15", + "node:timers/promises": ">= 16", + "_tls_common": ">= 0.11.13", + "node:_tls_common": [">= 14.18 && < 15", ">= 16"], + "_tls_legacy": ">= 0.11.3 && < 10", + "_tls_wrap": ">= 0.11.3", + "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"], + "tls": true, + "node:tls": [">= 14.18 && < 15", ">= 16"], + "trace_events": ">= 10", + "node:trace_events": [">= 14.18 && < 15", ">= 16"], + "tty": true, + "node:tty": [">= 14.18 && < 15", ">= 16"], + "url": true, + "node:url": [">= 14.18 && < 15", ">= 16"], + "util": true, + "node:util": [">= 14.18 && < 15", ">= 16"], + "util/types": ">= 15.3", + "node:util/types": ">= 16", + "v8/tools/arguments": ">= 10 && < 12", + "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8": ">= 1", + "node:v8": [">= 14.18 && < 15", ">= 16"], + "vm": true, + "node:vm": [">= 14.18 && < 15", ">= 16"], + "wasi": ">= 13.4 && < 13.5", + "worker_threads": ">= 11.7", + "node:worker_threads": [">= 14.18 && < 15", ">= 16"], + "zlib": ">= 0.5", + "node:zlib": [">= 14.18 && < 15", ">= 16"] +} diff --git a/node_modules/resolve/lib/homedir.js b/node_modules/resolve/lib/homedir.js new file mode 100644 index 0000000..5ffdf73 --- /dev/null +++ b/node_modules/resolve/lib/homedir.js @@ -0,0 +1,24 @@ +'use strict'; + +var os = require('os'); + +// adapted from https://github.com/sindresorhus/os-homedir/blob/11e089f4754db38bb535e5a8416320c4446e8cfd/index.js + +module.exports = os.homedir || function homedir() { + var home = process.env.HOME; + var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME; + + if (process.platform === 'win32') { + return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null; + } + + if (process.platform === 'darwin') { + return home || (user ? '/Users/' + user : null); + } + + if (process.platform === 'linux') { + return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); // eslint-disable-line no-extra-parens + } + + return home || null; +}; diff --git a/node_modules/resolve/lib/is-core.js b/node_modules/resolve/lib/is-core.js new file mode 100644 index 0000000..537f5c7 --- /dev/null +++ b/node_modules/resolve/lib/is-core.js @@ -0,0 +1,5 @@ +var isCoreModule = require('is-core-module'); + +module.exports = function isCore(x) { + return isCoreModule(x); +}; diff --git a/node_modules/resolve/lib/node-modules-paths.js b/node_modules/resolve/lib/node-modules-paths.js new file mode 100644 index 0000000..1cff010 --- /dev/null +++ b/node_modules/resolve/lib/node-modules-paths.js @@ -0,0 +1,42 @@ +var path = require('path'); +var parse = path.parse || require('path-parse'); // eslint-disable-line global-require + +var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { + var prefix = '/'; + if ((/^([A-Za-z]:)/).test(absoluteStart)) { + prefix = ''; + } else if ((/^\\\\/).test(absoluteStart)) { + prefix = '\\\\'; + } + + var paths = [absoluteStart]; + var parsed = parse(absoluteStart); + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = parse(parsed.dir); + } + + return paths.reduce(function (dirs, aPath) { + return dirs.concat(modules.map(function (moduleDir) { + return path.resolve(prefix, aPath, moduleDir); + })); + }, []); +}; + +module.exports = function nodeModulesPaths(start, opts, request) { + var modules = opts && opts.moduleDirectory + ? [].concat(opts.moduleDirectory) + : ['node_modules']; + + if (opts && typeof opts.paths === 'function') { + return opts.paths( + request, + start, + function () { return getNodeModulesDirs(start, modules); }, + opts + ); + } + + var dirs = getNodeModulesDirs(start, modules); + return opts && opts.paths ? dirs.concat(opts.paths) : dirs; +}; diff --git a/node_modules/resolve/lib/normalize-options.js b/node_modules/resolve/lib/normalize-options.js new file mode 100644 index 0000000..4b56904 --- /dev/null +++ b/node_modules/resolve/lib/normalize-options.js @@ -0,0 +1,10 @@ +module.exports = function (x, opts) { + /** + * This file is purposefully a passthrough. It's expected that third-party + * environments will override it at runtime in order to inject special logic + * into `resolve` (by manipulating the options). One such example is the PnP + * code path in Yarn. + */ + + return opts || {}; +}; diff --git a/node_modules/resolve/lib/sync.js b/node_modules/resolve/lib/sync.js new file mode 100644 index 0000000..0b6cd58 --- /dev/null +++ b/node_modules/resolve/lib/sync.js @@ -0,0 +1,208 @@ +var isCore = require('is-core-module'); +var fs = require('fs'); +var path = require('path'); +var getHomedir = require('./homedir'); +var caller = require('./caller'); +var nodeModulesPaths = require('./node-modules-paths'); +var normalizeOptions = require('./normalize-options'); + +var realpathFS = process.platform !== 'win32' && fs.realpathSync && typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; + +var homedir = getHomedir(); +var defaultPaths = function () { + return [ + path.join(homedir, '.node_modules'), + path.join(homedir, '.node_libraries') + ]; +}; + +var defaultIsFile = function isFile(file) { + try { + var stat = fs.statSync(file, { throwIfNoEntry: false }); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return !!stat && (stat.isFile() || stat.isFIFO()); +}; + +var defaultIsDir = function isDirectory(dir) { + try { + var stat = fs.statSync(dir, { throwIfNoEntry: false }); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return !!stat && stat.isDirectory(); +}; + +var defaultRealpathSync = function realpathSync(x) { + try { + return realpathFS(x); + } catch (realpathErr) { + if (realpathErr.code !== 'ENOENT') { + throw realpathErr; + } + } + return x; +}; + +var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { + if (opts && opts.preserveSymlinks === false) { + return realpathSync(x); + } + return x; +}; + +var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) { + var body = readFileSync(pkgfile); + try { + var pkg = JSON.parse(body); + return pkg; + } catch (jsonErr) {} +}; + +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); + } + return dirs; +}; + +module.exports = function resolveSync(x, options) { + if (typeof x !== 'string') { + throw new TypeError('Path must be a string.'); + } + var opts = normalizeOptions(x, options); + + var isFile = opts.isFile || defaultIsFile; + var readFileSync = opts.readFileSync || fs.readFileSync; + var isDirectory = opts.isDirectory || defaultIsDir; + var realpathSync = opts.realpathSync || defaultRealpathSync; + var readPackageSync = opts.readPackageSync || defaultReadPackageSync; + if (opts.readFileSync && opts.readPackageSync) { + throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.'); + } + var packageIterator = opts.packageIterator; + + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; + + opts.paths = opts.paths || defaultPaths(); + + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = maybeRealpathSync(realpathSync, path.resolve(basedir), opts); + + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + var res = path.resolve(absoluteStart, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + var m = loadAsFileSync(res) || loadAsDirectorySync(res); + if (m) return maybeRealpathSync(realpathSync, m, opts); + } else if (includeCoreModules && isCore(x)) { + return x; + } else { + var n = loadNodeModulesSync(x, absoluteStart); + if (n) return maybeRealpathSync(realpathSync, n, opts); + } + + var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + err.code = 'MODULE_NOT_FOUND'; + throw err; + + function loadAsFileSync(x) { + var pkg = loadpkg(path.dirname(x)); + + if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { + var rfile = path.relative(pkg.dir, x); + var r = opts.pathFilter(pkg.pkg, x, rfile); + if (r) { + x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign + } + } + + if (isFile(x)) { + return x; + } + + for (var i = 0; i < extensions.length; i++) { + var file = x + extensions[i]; + if (isFile(file)) { + return file; + } + } + } + + function loadpkg(dir) { + if (dir === '' || dir === '/') return; + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return; + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; + + var pkgfile = path.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json'); + + if (!isFile(pkgfile)) { + return loadpkg(path.dirname(dir)); + } + + var pkg = readPackageSync(readFileSync, pkgfile); + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment + } + + return { pkg: pkg, dir: dir }; + } + + function loadAsDirectorySync(x) { + var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); + if (isFile(pkgfile)) { + try { + var pkg = readPackageSync(readFileSync, pkgfile); + } catch (e) {} + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + throw mainError; + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + try { + var m = loadAsFileSync(path.resolve(x, pkg.main)); + if (m) return m; + var n = loadAsDirectorySync(path.resolve(x, pkg.main)); + if (n) return n; + } catch (e) {} + } + } + + return loadAsFileSync(path.join(x, '/index')); + } + + function loadNodeModulesSync(x, start) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); + + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + if (isDirectory(path.dirname(dir))) { + var m = loadAsFileSync(dir); + if (m) return m; + var n = loadAsDirectorySync(dir); + if (n) return n; + } + } + } +}; diff --git a/node_modules/resolve/package.json b/node_modules/resolve/package.json new file mode 100644 index 0000000..7177e0f --- /dev/null +++ b/node_modules/resolve/package.json @@ -0,0 +1,71 @@ +{ + "name": "resolve", + "description": "resolve like require.resolve() on behalf of files asynchronously and synchronously", + "version": "1.22.1", + "repository": { + "type": "git", + "url": "git://github.com/browserify/resolve.git" + }, + "bin": { + "resolve": "./bin/resolve" + }, + "main": "index.js", + "keywords": [ + "resolve", + "require", + "node", + "module" + ], + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest && cp node_modules/is-core-module/core.json ./lib/ ||:", + "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 --no-eslintrc -c .eslintrc . 'bin/**'", + "pretests-only": "cd ./test/resolver/nested_symlinks && node mylib/sync && node mylib/async", + "tests-only": "tape test/*.js", + "pretest": "npm run lint", + "test": "npm run --silent tests-only", + "posttest": "npm run test:multirepo && aud --production", + "test:multirepo": "cd ./test/resolver/multirepo && npm install && npm test" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "array.prototype.map": "^1.0.4", + "aud": "^2.0.0", + "copy-dir": "^1.3.0", + "eclint": "^2.8.1", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "mkdirp": "^0.5.5", + "mv": "^2.1.1", + "npmignore": "^0.3.0", + "object-keys": "^1.1.1", + "rimraf": "^2.7.1", + "safe-publish-latest": "^2.0.0", + "semver": "^6.3.0", + "tap": "0.4.13", + "tape": "^5.5.3", + "tmp": "^0.0.31" + }, + "license": "MIT", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "dependencies": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "appveyor.yml" + ] + } +} diff --git a/node_modules/resolve/readme.markdown b/node_modules/resolve/readme.markdown new file mode 100644 index 0000000..ad34d60 --- /dev/null +++ b/node_modules/resolve/readme.markdown @@ -0,0 +1,301 @@ +# resolve [![Version Badge][2]][1] + +implements the [node `require.resolve()` algorithm](https://nodejs.org/api/modules.html#modules_all_together) such that you can `require.resolve()` on behalf of a file asynchronously and synchronously + +[![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 + +asynchronously resolve: + +```js +var resolve = require('resolve/async'); // or, require('resolve') +resolve('tap', { basedir: __dirname }, function (err, res) { + if (err) console.error(err); + else console.log(res); +}); +``` + +``` +$ node example/async.js +/home/substack/projects/node-resolve/node_modules/tap/lib/main.js +``` + +synchronously resolve: + +```js +var resolve = require('resolve/sync'); // or, `require('resolve').sync +var res = resolve('tap', { basedir: __dirname }); +console.log(res); +``` + +``` +$ node example/sync.js +/home/substack/projects/node-resolve/node_modules/tap/lib/main.js +``` + +# methods + +```js +var resolve = require('resolve'); +var async = require('resolve/async'); +var sync = require('resolve/sync'); +``` + +For both the synchronous and asynchronous methods, errors may have any of the following `err.code` values: + +- `MODULE_NOT_FOUND`: the given path string (`id`) could not be resolved to a module +- `INVALID_BASEDIR`: the specified `opts.basedir` doesn't exist, or is not a directory +- `INVALID_PACKAGE_MAIN`: a `package.json` was encountered with an invalid `main` property (eg. not a string) + +## resolve(id, opts={}, cb) + +Asynchronously resolve the module path string `id` into `cb(err, res [, pkg])`, where `pkg` (if defined) is the data from `package.json`. + +options are: + +* opts.basedir - directory to begin resolving from + +* opts.package - `package.json` data applicable to the module being loaded + +* opts.extensions - array of file extensions to search in order + +* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search + +* opts.readFile - how to read files asynchronously + +* opts.isFile - function to asynchronously test whether a file exists + +* opts.isDirectory - function to asynchronously test whether a file exists and is a directory + +* opts.realpath - function to asynchronously resolve a potential symlink to its real path + +* `opts.readPackage(readFile, pkgfile, cb)` - function to asynchronously read and parse a package.json file + * readFile - the passed `opts.readFile` or `fs.readFile` if not specified + * pkgfile - path to package.json + * cb - callback + +* `opts.packageFilter(pkg, pkgfile, dir)` - transform the parsed package.json contents before looking at the "main" field + * pkg - package data + * pkgfile - path to package.json + * dir - directory that contains package.json + +* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package + * pkg - package data + * path - the path being resolved + * relativePath - the path relative from the package.json location + * returns - a relative path that will be joined from the package.json location + +* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this) + + For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function + * request - the import specifier being resolved + * start - lookup path + * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this) + * request - the import specifier being resolved + * start - lookup path + * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"` + +* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving. +This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag. +**Note:** this property is currently `true` by default but it will be changed to +`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*. + +default `opts` values: + +```js +{ + paths: [], + basedir: __dirname, + extensions: ['.js'], + includeCoreModules: true, + readFile: fs.readFile, + isFile: function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }, + isDirectory: function isDirectory(dir, cb) { + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }, + realpath: function realpath(file, cb) { + var realpath = typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; + realpath(file, function (realPathErr, realPath) { + if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr); + else cb(null, realPathErr ? file : realPath); + }); + }, + readPackage: function defaultReadPackage(readFile, pkgfile, cb) { + readFile(pkgfile, function (readFileErr, body) { + if (readFileErr) cb(readFileErr); + else { + try { + var pkg = JSON.parse(body); + cb(null, pkg); + } catch (jsonErr) { + cb(null); + } + } + }); + }, + moduleDirectory: 'node_modules', + preserveSymlinks: true +} +``` + +## resolve.sync(id, opts) + +Synchronously resolve the module path string `id`, returning the result and +throwing an error when `id` can't be resolved. + +options are: + +* opts.basedir - directory to begin resolving from + +* opts.extensions - array of file extensions to search in order + +* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search + +* opts.readFileSync - how to read files synchronously + +* opts.isFile - function to synchronously test whether a file exists + +* opts.isDirectory - function to synchronously test whether a file exists and is a directory + +* opts.realpathSync - function to synchronously resolve a potential symlink to its real path + +* `opts.readPackageSync(readFileSync, pkgfile)` - function to synchronously read and parse a package.json file + * readFileSync - the passed `opts.readFileSync` or `fs.readFileSync` if not specified + * pkgfile - path to package.json + +* `opts.packageFilter(pkg, dir)` - transform the parsed package.json contents before looking at the "main" field + * pkg - package data + * dir - directory that contains package.json (Note: the second argument will change to "pkgfile" in v2) + +* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package + * pkg - package data + * path - the path being resolved + * relativePath - the path relative from the package.json location + * returns - a relative path that will be joined from the package.json location + +* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this) + + For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function + * request - the import specifier being resolved + * start - lookup path + * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this) + * request - the import specifier being resolved + * start - lookup path + * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"` + +* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving. +This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag. +**Note:** this property is currently `true` by default but it will be changed to +`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*. + +default `opts` values: + +```js +{ + paths: [], + basedir: __dirname, + extensions: ['.js'], + includeCoreModules: true, + readFileSync: fs.readFileSync, + isFile: function isFile(file) { + try { + var stat = fs.statSync(file); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isFile() || stat.isFIFO(); + }, + isDirectory: function isDirectory(dir) { + try { + var stat = fs.statSync(dir); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isDirectory(); + }, + realpathSync: function realpathSync(file) { + try { + var realpath = typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; + return realpath(file); + } catch (realPathErr) { + if (realPathErr.code !== 'ENOENT') { + throw realPathErr; + } + } + return file; + }, + readPackageSync: function defaultReadPackageSync(readFileSync, pkgfile) { + var body = readFileSync(pkgfile); + try { + var pkg = JSON.parse(body); + return pkg; + } catch (jsonErr) {} + }, + moduleDirectory: 'node_modules', + preserveSymlinks: true +} +``` + +# install + +With [npm](https://npmjs.org) do: + +```sh +npm install resolve +``` + +# license + +MIT + +[1]: https://npmjs.org/package/resolve +[2]: https://versionbadg.es/browserify/resolve.svg +[5]: https://david-dm.org/browserify/resolve.svg +[6]: https://david-dm.org/browserify/resolve +[7]: https://david-dm.org/browserify/resolve/dev-status.svg +[8]: https://david-dm.org/browserify/resolve#info=devDependencies +[11]: https://nodei.co/npm/resolve.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/resolve.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/resolve.svg +[downloads-url]: https://npm-stat.com/charts.html?package=resolve +[codecov-image]: https://codecov.io/gh/browserify/resolve/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/browserify/resolve/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/browserify/resolve +[actions-url]: https://github.com/browserify/resolve/actions diff --git a/node_modules/resolve/sync.js b/node_modules/resolve/sync.js new file mode 100644 index 0000000..cd0ee04 --- /dev/null +++ b/node_modules/resolve/sync.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/sync'); diff --git a/node_modules/resolve/test/core.js b/node_modules/resolve/test/core.js new file mode 100644 index 0000000..a477adc --- /dev/null +++ b/node_modules/resolve/test/core.js @@ -0,0 +1,88 @@ +var test = require('tape'); +var keys = require('object-keys'); +var semver = require('semver'); + +var resolve = require('../'); + +var brokenNode = semver.satisfies(process.version, '11.11 - 11.13'); + +test('core modules', function (t) { + t.test('isCore()', function (st) { + st.ok(resolve.isCore('fs')); + st.ok(resolve.isCore('net')); + st.ok(resolve.isCore('http')); + + st.ok(!resolve.isCore('seq')); + st.ok(!resolve.isCore('../')); + + st.ok(!resolve.isCore('toString')); + + st.end(); + }); + + t.test('core list', function (st) { + var cores = keys(resolve.core); + st.plan(cores.length); + + for (var i = 0; i < cores.length; ++i) { + var mod = cores[i]; + // note: this must be require, not require.resolve, due to https://github.com/nodejs/node/issues/43274 + var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func + t.comment(mod + ': ' + resolve.core[mod]); + if (resolve.core[mod]) { + st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw'); + } else if (brokenNode) { + st.ok(true, 'this version of node is broken: attempting to require things that fail to resolve breaks "home_paths" tests'); + } else { + st.throws(requireFunc, mod + ' not supported; requiring throws'); + } + } + + st.end(); + }); + + t.test('core via repl module', { skip: !resolve.core.repl }, function (st) { + var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle + if (!libs) { + st.skip('module.builtinModules does not exist'); + return st.end(); + } + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + st.ok(resolve.core[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + } + st.end(); + }); + + t.test('core via builtinModules list', { skip: !resolve.core.module }, function (st) { + var libs = require('module').builtinModules; + if (!libs) { + st.skip('module.builtinModules does not exist'); + return st.end(); + } + var blacklist = [ + '_debug_agent', + 'v8/tools/tickprocessor-driver', + 'v8/tools/SourceMap', + 'v8/tools/tickprocessor', + 'v8/tools/profile' + ]; + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + if (blacklist.indexOf(mod) === -1) { + st.ok(resolve.core[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + } + } + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/resolve/test/dotdot.js b/node_modules/resolve/test/dotdot.js new file mode 100644 index 0000000..3080665 --- /dev/null +++ b/node_modules/resolve/test/dotdot.js @@ -0,0 +1,29 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('dotdot', function (t) { + t.plan(4); + var dir = path.join(__dirname, '/dotdot/abc'); + + resolve('..', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'dotdot/index.js')); + }); + + resolve('.', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('dotdot sync', function (t) { + t.plan(2); + var dir = path.join(__dirname, '/dotdot/abc'); + + var a = resolve.sync('..', { basedir: dir }); + t.equal(a, path.join(__dirname, 'dotdot/index.js')); + + var b = resolve.sync('.', { basedir: dir }); + t.equal(b, path.join(dir, 'index.js')); +}); diff --git a/node_modules/resolve/test/dotdot/abc/index.js b/node_modules/resolve/test/dotdot/abc/index.js new file mode 100644 index 0000000..67f2534 --- /dev/null +++ b/node_modules/resolve/test/dotdot/abc/index.js @@ -0,0 +1,2 @@ +var x = require('..'); +console.log(x); diff --git a/node_modules/resolve/test/dotdot/index.js b/node_modules/resolve/test/dotdot/index.js new file mode 100644 index 0000000..643f9fc --- /dev/null +++ b/node_modules/resolve/test/dotdot/index.js @@ -0,0 +1 @@ +module.exports = 'whatever'; diff --git a/node_modules/resolve/test/faulty_basedir.js b/node_modules/resolve/test/faulty_basedir.js new file mode 100644 index 0000000..5f2141a --- /dev/null +++ b/node_modules/resolve/test/faulty_basedir.js @@ -0,0 +1,29 @@ +var test = require('tape'); +var path = require('path'); +var resolve = require('../'); + +test('faulty basedir must produce error in windows', { skip: process.platform !== 'win32' }, function (t) { + t.plan(1); + + var resolverDir = 'C:\\a\\b\\c\\d'; + + resolve('tape/lib/test.js', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(!!err, true); + }); +}); + +test('non-existent basedir should not throw when preserveSymlinks is false', function (t) { + t.plan(2); + + var opts = { + basedir: path.join(path.sep, 'unreal', 'path', 'that', 'does', 'not', 'exist'), + preserveSymlinks: false + }; + + var module = './dotdot/abc'; + + resolve(module, opts, function (err, res) { + t.equal(err.code, 'MODULE_NOT_FOUND'); + t.equal(res, undefined); + }); +}); diff --git a/node_modules/resolve/test/filter.js b/node_modules/resolve/test/filter.js new file mode 100644 index 0000000..8f8cccd --- /dev/null +++ b/node_modules/resolve/test/filter.js @@ -0,0 +1,34 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('filter', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + var packageFilterArgs; + resolve('./baz', { + basedir: dir, + packageFilter: function (pkg, pkgfile) { + pkg.main = 'doom'; // eslint-disable-line no-param-reassign + packageFilterArgs = [pkg, pkgfile]; + return pkg; + } + }, function (err, res, pkg) { + if (err) t.fail(err); + + t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works'); + + var packageData = packageFilterArgs[0]; + t.equal(pkg, packageData, 'first packageFilter argument is "pkg"'); + t.equal(packageData.main, 'doom', 'package "main" was altered'); + + var packageFile = packageFilterArgs[1]; + t.equal( + packageFile, + path.join(dir, 'baz/package.json'), + 'second packageFilter argument is "pkgfile"' + ); + + t.end(); + }); +}); diff --git a/node_modules/resolve/test/filter_sync.js b/node_modules/resolve/test/filter_sync.js new file mode 100644 index 0000000..8a43b98 --- /dev/null +++ b/node_modules/resolve/test/filter_sync.js @@ -0,0 +1,33 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('filter', function (t) { + var dir = path.join(__dirname, 'resolver'); + var packageFilterArgs; + var res = resolve.sync('./baz', { + basedir: dir, + // NOTE: in v2.x, this will be `pkg, pkgfile, dir`, but must remain "broken" here in v1.x for compatibility + packageFilter: function (pkg, /*pkgfile,*/ dir) { // eslint-disable-line spaced-comment + pkg.main = 'doom'; // eslint-disable-line no-param-reassign + packageFilterArgs = 'is 1.x' ? [pkg, dir] : [pkg, pkgfile, dir]; // eslint-disable-line no-constant-condition, no-undef + return pkg; + } + }); + + t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works'); + + var packageData = packageFilterArgs[0]; + t.equal(packageData.main, 'doom', 'package "main" was altered'); + + if (!'is 1.x') { // eslint-disable-line no-constant-condition + var packageFile = packageFilterArgs[1]; + t.equal(packageFile, path.join(dir, 'baz', 'package.json'), 'package.json path is correct'); + } + + var packageDir = packageFilterArgs['is 1.x' ? 1 : 2]; // eslint-disable-line no-constant-condition + // eslint-disable-next-line no-constant-condition + t.equal(packageDir, path.join(dir, 'baz'), ('is 1.x' ? 'second' : 'third') + ' packageFilter argument is "dir"'); + + t.end(); +}); diff --git a/node_modules/resolve/test/home_paths.js b/node_modules/resolve/test/home_paths.js new file mode 100644 index 0000000..3b8c9b3 --- /dev/null +++ b/node_modules/resolve/test/home_paths.js @@ -0,0 +1,127 @@ +'use strict'; + +var fs = require('fs'); +var homedir = require('../lib/homedir'); +var path = require('path'); + +var test = require('tape'); +var mkdirp = require('mkdirp'); +var rimraf = require('rimraf'); +var mv = require('mv'); +var copyDir = require('copy-dir'); +var tmp = require('tmp'); + +var HOME = homedir(); + +var hnm = path.join(HOME, '.node_modules'); +var hnl = path.join(HOME, '.node_libraries'); + +var resolve = require('../async'); + +function makeDir(t, dir, cb) { + mkdirp(dir, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function cleanup() { + rimraf.sync(dir); + }); + cb(); + } + }); +} + +function makeTempDir(t, dir, cb) { + if (fs.existsSync(dir)) { + var tmpResult = tmp.dirSync(); + t.teardown(tmpResult.removeCallback); + var backup = path.join(tmpResult.name, path.basename(dir)); + mv(dir, backup, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function () { + mv(backup, dir, cb); + }); + makeDir(t, dir, cb); + } + }); + } else { + makeDir(t, dir, cb); + } +} + +test('homedir module paths', function (t) { + t.plan(7); + + makeTempDir(t, hnm, function (err) { + t.error(err, 'no error with HNM temp dir'); + if (err) { + return t.end(); + } + + var bazHNMDir = path.join(hnm, 'baz'); + var dotMainDir = path.join(hnm, 'dot_main'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNMDir); + copyDir.sync(path.join(__dirname, 'resolver/dot_main'), dotMainDir); + + var bazPkg = { name: 'baz', main: 'quux.js' }; + var dotMainPkg = { main: 'index' }; + + var bazHNMmain = path.join(bazHNMDir, 'quux.js'); + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + var dotMainMain = path.join(dotMainDir, 'index.js'); + t.equal(require.resolve('dot_main'), dotMainMain, 'sanity check: require.resolve finds `dot_main`'); + + makeTempDir(t, hnl, function (err) { + t.error(err, 'no error with HNL temp dir'); + if (err) { + return t.end(); + } + var bazHNLDir = path.join(hnl, 'baz'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNLDir); + + var dotSlashMainDir = path.join(hnl, 'dot_slash_main'); + var dotSlashMainMain = path.join(dotSlashMainDir, 'index.js'); + var dotSlashMainPkg = { main: 'index' }; + copyDir.sync(path.join(__dirname, 'resolver/dot_slash_main'), dotSlashMainDir); + + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + t.equal(require.resolve('dot_slash_main'), dotSlashMainMain, 'sanity check: require.resolve finds HNL `dot_slash_main`'); + + t.test('with temp dirs', function (st) { + st.plan(3); + + st.test('just in `$HOME/.node_modules`', function (s2t) { + s2t.plan(3); + + resolve('dot_main', function (err, res, pkg) { + s2t.error(err, 'no error resolving `dot_main`'); + s2t.equal(res, dotMainMain, '`dot_main` resolves in `$HOME/.node_modules`'); + s2t.deepEqual(pkg, dotMainPkg); + }); + }); + + st.test('just in `$HOME/.node_libraries`', function (s2t) { + s2t.plan(3); + + resolve('dot_slash_main', function (err, res, pkg) { + s2t.error(err, 'no error resolving `dot_slash_main`'); + s2t.equal(res, dotSlashMainMain, '`dot_slash_main` resolves in `$HOME/.node_libraries`'); + s2t.deepEqual(pkg, dotSlashMainPkg); + }); + }); + + st.test('in `$HOME/.node_libraries` and `$HOME/.node_modules`', function (s2t) { + s2t.plan(3); + + resolve('baz', function (err, res, pkg) { + s2t.error(err, 'no error resolving `baz`'); + s2t.equal(res, bazHNMmain, '`baz` resolves in `$HOME/.node_modules` when in both'); + s2t.deepEqual(pkg, bazPkg); + }); + }); + }); + }); + }); +}); diff --git a/node_modules/resolve/test/home_paths_sync.js b/node_modules/resolve/test/home_paths_sync.js new file mode 100644 index 0000000..5d2c56f --- /dev/null +++ b/node_modules/resolve/test/home_paths_sync.js @@ -0,0 +1,114 @@ +'use strict'; + +var fs = require('fs'); +var homedir = require('../lib/homedir'); +var path = require('path'); + +var test = require('tape'); +var mkdirp = require('mkdirp'); +var rimraf = require('rimraf'); +var mv = require('mv'); +var copyDir = require('copy-dir'); +var tmp = require('tmp'); + +var HOME = homedir(); + +var hnm = path.join(HOME, '.node_modules'); +var hnl = path.join(HOME, '.node_libraries'); + +var resolve = require('../sync'); + +function makeDir(t, dir, cb) { + mkdirp(dir, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function cleanup() { + rimraf.sync(dir); + }); + cb(); + } + }); +} + +function makeTempDir(t, dir, cb) { + if (fs.existsSync(dir)) { + var tmpResult = tmp.dirSync(); + t.teardown(tmpResult.removeCallback); + var backup = path.join(tmpResult.name, path.basename(dir)); + mv(dir, backup, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function () { + mv(backup, dir, cb); + }); + makeDir(t, dir, cb); + } + }); + } else { + makeDir(t, dir, cb); + } +} + +test('homedir module paths', function (t) { + t.plan(7); + + makeTempDir(t, hnm, function (err) { + t.error(err, 'no error with HNM temp dir'); + if (err) { + return t.end(); + } + + var bazHNMDir = path.join(hnm, 'baz'); + var dotMainDir = path.join(hnm, 'dot_main'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNMDir); + copyDir.sync(path.join(__dirname, 'resolver/dot_main'), dotMainDir); + + var bazHNMmain = path.join(bazHNMDir, 'quux.js'); + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + var dotMainMain = path.join(dotMainDir, 'index.js'); + t.equal(require.resolve('dot_main'), dotMainMain, 'sanity check: require.resolve finds `dot_main`'); + + makeTempDir(t, hnl, function (err) { + t.error(err, 'no error with HNL temp dir'); + if (err) { + return t.end(); + } + var bazHNLDir = path.join(hnl, 'baz'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNLDir); + + var dotSlashMainDir = path.join(hnl, 'dot_slash_main'); + var dotSlashMainMain = path.join(dotSlashMainDir, 'index.js'); + copyDir.sync(path.join(__dirname, 'resolver/dot_slash_main'), dotSlashMainDir); + + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + t.equal(require.resolve('dot_slash_main'), dotSlashMainMain, 'sanity check: require.resolve finds HNL `dot_slash_main`'); + + t.test('with temp dirs', function (st) { + st.plan(3); + + st.test('just in `$HOME/.node_modules`', function (s2t) { + s2t.plan(1); + + var res = resolve('dot_main'); + s2t.equal(res, dotMainMain, '`dot_main` resolves in `$HOME/.node_modules`'); + }); + + st.test('just in `$HOME/.node_libraries`', function (s2t) { + s2t.plan(1); + + var res = resolve('dot_slash_main'); + s2t.equal(res, dotSlashMainMain, '`dot_slash_main` resolves in `$HOME/.node_libraries`'); + }); + + st.test('in `$HOME/.node_libraries` and `$HOME/.node_modules`', function (s2t) { + s2t.plan(1); + + var res = resolve('baz'); + s2t.equal(res, bazHNMmain, '`baz` resolves in `$HOME/.node_modules` when in both'); + }); + }); + }); + }); +}); diff --git a/node_modules/resolve/test/mock.js b/node_modules/resolve/test/mock.js new file mode 100644 index 0000000..6116275 --- /dev/null +++ b/node_modules/resolve/test/mock.js @@ -0,0 +1,315 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('mock', function (t) { + t.plan(8); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('../baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('mock from package', function (t) { + t.plan(8); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, file)); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[file]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg && pkg.main, 'bar'); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg && pkg.main, 'bar'); + }); + + resolve('baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('../baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('mock package', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('bar', opts('/foo'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + t.equal(pkg && pkg.main, './baz.js'); + }); +}); + +test('mock package from package', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('bar', opts('/foo'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + t.equal(pkg && pkg.main, './baz.js'); + }); +}); + +test('symlinked', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + dirs[path.resolve('/foo/bar/symlinked')] = true; + + function opts(basedir) { + return { + preserveSymlinks: false, + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + var resolved = path.resolve(file); + + if (resolved.indexOf('symlinked') >= 0) { + cb(null, resolved); + return; + } + + var ext = path.extname(resolved); + + if (ext) { + var dir = path.dirname(resolved); + var base = path.basename(resolved); + cb(null, path.join(dir, 'symlinked', base)); + } else { + cb(null, path.join(resolved, 'symlinked')); + } + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/symlinked/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/symlinked/baz.js')); + t.equal(pkg, undefined); + }); +}); + +test('readPackage', function (t) { + t.plan(3); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop'; + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + t.test('with readFile', function (st) { + st.plan(3); + + resolve('bar', opts('/foo'), function (err, res, pkg) { + st.error(err); + st.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + st.equal(pkg && pkg.main, './baz.js'); + }); + }); + + var readPackage = function (readFile, file, cb) { + var barPackage = path.join('bar', 'package.json'); + if (file.slice(-barPackage.length) === barPackage) { + cb(null, { main: './something-else.js' }); + } else { + cb(null, JSON.parse(files[path.resolve(file)])); + } + }; + + t.test('with readPackage', function (st) { + st.plan(3); + + var options = opts('/foo'); + delete options.readFile; + options.readPackage = readPackage; + resolve('bar', options, function (err, res, pkg) { + st.error(err); + st.equal(res, path.resolve('/foo/node_modules/bar/something-else.js')); + st.equal(pkg && pkg.main, './something-else.js'); + }); + }); + + t.test('with readFile and readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + options.readPackage = readPackage; + resolve('bar', options, function (err) { + st.throws(function () { throw err; }, TypeError, 'errors when both readFile and readPackage are provided'); + }); + }); +}); diff --git a/node_modules/resolve/test/mock_sync.js b/node_modules/resolve/test/mock_sync.js new file mode 100644 index 0000000..c5a7e2a --- /dev/null +++ b/node_modules/resolve/test/mock_sync.js @@ -0,0 +1,214 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('mock', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + + t.equal( + resolve.sync('./baz', opts('/foo/bar')), + path.resolve('/foo/bar/baz.js') + ); + + t.equal( + resolve.sync('./baz.js', opts('/foo/bar')), + path.resolve('/foo/bar/baz.js') + ); + + t.throws(function () { + resolve.sync('baz', opts('/foo/bar')); + }); + + t.throws(function () { + resolve.sync('../baz', opts('/foo/bar')); + }); +}); + +test('mock package', function (t) { + t.plan(1); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + + t.equal( + resolve.sync('bar', opts('/foo')), + path.resolve('/foo/node_modules/bar/baz.js') + ); +}); + +test('symlinked', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + dirs[path.resolve('/foo/bar/symlinked')] = true; + + function opts(basedir) { + return { + preserveSymlinks: false, + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + var resolved = path.resolve(file); + + if (resolved.indexOf('symlinked') >= 0) { + return resolved; + } + + var ext = path.extname(resolved); + + if (ext) { + var dir = path.dirname(resolved); + var base = path.basename(resolved); + return path.join(dir, 'symlinked', base); + } + return path.join(resolved, 'symlinked'); + } + }; + } + + t.equal( + resolve.sync('./baz', opts('/foo/bar')), + path.resolve('/foo/bar/symlinked/baz.js') + ); + + t.equal( + resolve.sync('./baz.js', opts('/foo/bar')), + path.resolve('/foo/bar/symlinked/baz.js') + ); +}); + +test('readPackageSync', function (t) { + t.plan(3); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop'; + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir, useReadPackage) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: useReadPackage ? null : function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + t.test('with readFile', function (st) { + st.plan(1); + + st.equal( + resolve.sync('bar', opts('/foo')), + path.resolve('/foo/node_modules/bar/baz.js') + ); + }); + + var readPackageSync = function (readFileSync, file) { + if (file.indexOf(path.join('bar', 'package.json')) >= 0) { + return { main: './something-else.js' }; + } + return JSON.parse(files[path.resolve(file)]); + }; + + t.test('with readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + delete options.readFileSync; + options.readPackageSync = readPackageSync; + + st.equal( + resolve.sync('bar', options), + path.resolve('/foo/node_modules/bar/something-else.js') + ); + }); + + t.test('with readFile and readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + options.readPackageSync = readPackageSync; + st.throws( + function () { resolve.sync('bar', options); }, + TypeError, + 'errors when both readFile and readPackage are provided' + ); + }); +}); + diff --git a/node_modules/resolve/test/module_dir.js b/node_modules/resolve/test/module_dir.js new file mode 100644 index 0000000..b50e5bb --- /dev/null +++ b/node_modules/resolve/test/module_dir.js @@ -0,0 +1,56 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('moduleDirectory strings', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'module_dir'); + var xopts = { + basedir: dir, + moduleDirectory: 'xmodules' + }; + resolve('aaa', xopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/xmodules/aaa/index.js')); + }); + + var yopts = { + basedir: dir, + moduleDirectory: 'ymodules' + }; + resolve('aaa', yopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/ymodules/aaa/index.js')); + }); +}); + +test('moduleDirectory array', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'module_dir'); + var aopts = { + basedir: dir, + moduleDirectory: ['xmodules', 'ymodules', 'zmodules'] + }; + resolve('aaa', aopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/xmodules/aaa/index.js')); + }); + + var bopts = { + basedir: dir, + moduleDirectory: ['zmodules', 'ymodules', 'xmodules'] + }; + resolve('aaa', bopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/ymodules/aaa/index.js')); + }); + + var copts = { + basedir: dir, + moduleDirectory: ['xmodules', 'ymodules', 'zmodules'] + }; + resolve('bbb', copts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/zmodules/bbb/main.js')); + }); +}); diff --git a/node_modules/resolve/test/module_dir/xmodules/aaa/index.js b/node_modules/resolve/test/module_dir/xmodules/aaa/index.js new file mode 100644 index 0000000..dd7cf7b --- /dev/null +++ b/node_modules/resolve/test/module_dir/xmodules/aaa/index.js @@ -0,0 +1 @@ +module.exports = function (x) { return x * 100; }; diff --git a/node_modules/resolve/test/module_dir/ymodules/aaa/index.js b/node_modules/resolve/test/module_dir/ymodules/aaa/index.js new file mode 100644 index 0000000..ef2d4d4 --- /dev/null +++ b/node_modules/resolve/test/module_dir/ymodules/aaa/index.js @@ -0,0 +1 @@ +module.exports = function (x) { return x + 100; }; diff --git a/node_modules/resolve/test/module_dir/zmodules/bbb/main.js b/node_modules/resolve/test/module_dir/zmodules/bbb/main.js new file mode 100644 index 0000000..e8ba629 --- /dev/null +++ b/node_modules/resolve/test/module_dir/zmodules/bbb/main.js @@ -0,0 +1 @@ +module.exports = function (n) { return n * 111; }; diff --git a/node_modules/resolve/test/module_dir/zmodules/bbb/package.json b/node_modules/resolve/test/module_dir/zmodules/bbb/package.json new file mode 100644 index 0000000..c13b8cf --- /dev/null +++ b/node_modules/resolve/test/module_dir/zmodules/bbb/package.json @@ -0,0 +1,3 @@ +{ + "main": "main.js" +} diff --git a/node_modules/resolve/test/node-modules-paths.js b/node_modules/resolve/test/node-modules-paths.js new file mode 100644 index 0000000..675441d --- /dev/null +++ b/node_modules/resolve/test/node-modules-paths.js @@ -0,0 +1,143 @@ +var test = require('tape'); +var path = require('path'); +var parse = path.parse || require('path-parse'); +var keys = require('object-keys'); + +var nodeModulesPaths = require('../lib/node-modules-paths'); + +var verifyDirs = function verifyDirs(t, start, dirs, moduleDirectories, paths) { + var moduleDirs = [].concat(moduleDirectories || 'node_modules'); + if (paths) { + for (var k = 0; k < paths.length; ++k) { + moduleDirs.push(path.basename(paths[k])); + } + } + + var foundModuleDirs = {}; + var uniqueDirs = {}; + var parsedDirs = {}; + for (var i = 0; i < dirs.length; ++i) { + var parsed = parse(dirs[i]); + if (!foundModuleDirs[parsed.base]) { foundModuleDirs[parsed.base] = 0; } + foundModuleDirs[parsed.base] += 1; + parsedDirs[parsed.dir] = true; + uniqueDirs[dirs[i]] = true; + } + t.equal(keys(parsedDirs).length >= start.split(path.sep).length, true, 'there are >= dirs than "start" has'); + var foundModuleDirNames = keys(foundModuleDirs); + t.deepEqual(foundModuleDirNames, moduleDirs, 'all desired module dirs were found'); + t.equal(keys(uniqueDirs).length, dirs.length, 'all dirs provided were unique'); + + var counts = {}; + for (var j = 0; j < foundModuleDirNames.length; ++j) { + counts[foundModuleDirs[j]] = true; + } + t.equal(keys(counts).length, 1, 'all found module directories had the same count'); +}; + +test('node-modules-paths', function (t) { + t.test('no options', function (t) { + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start); + + verifyDirs(t, start, dirs); + + t.end(); + }); + + t.test('empty options', function (t) { + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, {}); + + verifyDirs(t, start, dirs); + + t.end(); + }); + + t.test('with paths=array option', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var dirs = nodeModulesPaths(start, { paths: paths }); + + verifyDirs(t, start, dirs, null, paths); + + t.end(); + }); + + t.test('with paths=function option', function (t) { + var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) { + return getNodeModulesDirs().concat(path.join(absoluteStart, 'not node modules', request)); + }; + + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, { paths: paths }, 'pkg'); + + verifyDirs(t, start, dirs, null, [path.join(start, 'not node modules', 'pkg')]); + + t.end(); + }); + + t.test('with paths=function skipping node modules resolution', function (t) { + var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) { + return []; + }; + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, { paths: paths }); + t.deepEqual(dirs, [], 'no node_modules was computed'); + t.end(); + }); + + t.test('with moduleDirectory option', function (t) { + var start = path.join(__dirname, 'resolver'); + var moduleDirectory = 'not node modules'; + var dirs = nodeModulesPaths(start, { moduleDirectory: moduleDirectory }); + + verifyDirs(t, start, dirs, moduleDirectory); + + t.end(); + }); + + t.test('with 1 moduleDirectory and paths options', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var moduleDirectory = 'not node modules'; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectory }); + + verifyDirs(t, start, dirs, moduleDirectory, paths); + + t.end(); + }); + + t.test('with 1+ moduleDirectory and paths options', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var moduleDirectories = ['not node modules', 'other modules']; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + verifyDirs(t, start, dirs, moduleDirectories, paths); + + t.end(); + }); + + t.test('combine paths correctly on Windows', function (t) { + var start = 'C:\\Users\\username\\myProject\\src'; + var paths = []; + var moduleDirectories = ['node_modules', start]; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir'); + + t.end(); + }); + + t.test('combine paths correctly on non-Windows', { skip: process.platform === 'win32' }, function (t) { + var start = '/Users/username/git/myProject/src'; + var paths = []; + var moduleDirectories = ['node_modules', '/Users/username/git/myProject/src']; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir'); + + t.end(); + }); +}); diff --git a/node_modules/resolve/test/node_path.js b/node_modules/resolve/test/node_path.js new file mode 100644 index 0000000..e463d6c --- /dev/null +++ b/node_modules/resolve/test/node_path.js @@ -0,0 +1,70 @@ +var fs = require('fs'); +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('$NODE_PATH', function (t) { + t.plan(8); + + var isDir = function (dir, cb) { + if (dir === '/node_path' || dir === 'node_path/x') { + return cb(null, true); + } + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }; + + resolve('aaa', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/x/aaa/index.js'), 'aaa resolves'); + }); + + resolve('bbb', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/y/bbb/index.js'), 'bbb resolves'); + }); + + resolve('ccc', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/x/ccc/index.js'), 'ccc resolves'); + }); + + // ensure that relative paths still resolve against the regular `node_modules` correctly + resolve('tap', { + paths: [ + 'node_path' + ], + basedir: path.join(__dirname, 'node_path/x'), + isDirectory: isDir + }, function (err, res) { + var root = require('tap/package.json').main; // eslint-disable-line global-require + t.error(err); + t.equal(res, path.resolve(__dirname, '..', 'node_modules/tap', root), 'tap resolves'); + }); +}); diff --git a/node_modules/resolve/test/node_path/x/aaa/index.js b/node_modules/resolve/test/node_path/x/aaa/index.js new file mode 100644 index 0000000..ad70d0b --- /dev/null +++ b/node_modules/resolve/test/node_path/x/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'A'; diff --git a/node_modules/resolve/test/node_path/x/ccc/index.js b/node_modules/resolve/test/node_path/x/ccc/index.js new file mode 100644 index 0000000..a64132e --- /dev/null +++ b/node_modules/resolve/test/node_path/x/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'C'; diff --git a/node_modules/resolve/test/node_path/y/bbb/index.js b/node_modules/resolve/test/node_path/y/bbb/index.js new file mode 100644 index 0000000..4d0f32e --- /dev/null +++ b/node_modules/resolve/test/node_path/y/bbb/index.js @@ -0,0 +1 @@ +module.exports = 'B'; diff --git a/node_modules/resolve/test/node_path/y/ccc/index.js b/node_modules/resolve/test/node_path/y/ccc/index.js new file mode 100644 index 0000000..793315e --- /dev/null +++ b/node_modules/resolve/test/node_path/y/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'CY'; diff --git a/node_modules/resolve/test/nonstring.js b/node_modules/resolve/test/nonstring.js new file mode 100644 index 0000000..ef63c40 --- /dev/null +++ b/node_modules/resolve/test/nonstring.js @@ -0,0 +1,9 @@ +var test = require('tape'); +var resolve = require('../'); + +test('nonstring', function (t) { + t.plan(1); + resolve(555, function (err, res, pkg) { + t.ok(err); + }); +}); diff --git a/node_modules/resolve/test/pathfilter.js b/node_modules/resolve/test/pathfilter.js new file mode 100644 index 0000000..16519ae --- /dev/null +++ b/node_modules/resolve/test/pathfilter.js @@ -0,0 +1,75 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +var resolverDir = path.join(__dirname, '/pathfilter/deep_ref'); + +var pathFilterFactory = function (t) { + return function (pkg, x, remainder) { + t.equal(pkg.version, '1.2.3'); + t.equal(x, path.join(resolverDir, 'node_modules/deep/ref')); + t.equal(remainder, 'ref'); + return 'alt'; + }; +}; + +test('#62: deep module references and the pathFilter', function (t) { + t.test('deep/ref.js', function (st) { + st.plan(3); + + resolve('deep/ref', { basedir: resolverDir }, function (err, res, pkg) { + if (err) st.fail(err); + + st.equal(pkg.version, '1.2.3'); + st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js')); + }); + + var res = resolve.sync('deep/ref', { basedir: resolverDir }); + st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js')); + }); + + t.test('deep/deeper/ref', function (st) { + st.plan(4); + + resolve( + 'deep/deeper/ref', + { basedir: resolverDir }, + function (err, res, pkg) { + if (err) t.fail(err); + st.notEqual(pkg, undefined); + st.equal(pkg.version, '1.2.3'); + st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js')); + } + ); + + var res = resolve.sync( + 'deep/deeper/ref', + { basedir: resolverDir } + ); + st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js')); + }); + + t.test('deep/ref alt', function (st) { + st.plan(8); + + var pathFilter = pathFilterFactory(st); + + var res = resolve.sync( + 'deep/ref', + { basedir: resolverDir, pathFilter: pathFilter } + ); + st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js')); + + resolve( + 'deep/ref', + { basedir: resolverDir, pathFilter: pathFilter }, + function (err, res, pkg) { + if (err) st.fail(err); + st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js')); + st.end(); + } + ); + }); + + t.end(); +}); diff --git a/node_modules/resolve/test/pathfilter/deep_ref/main.js b/node_modules/resolve/test/pathfilter/deep_ref/main.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/precedence.js b/node_modules/resolve/test/precedence.js new file mode 100644 index 0000000..2febb59 --- /dev/null +++ b/node_modules/resolve/test/precedence.js @@ -0,0 +1,23 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('precedence', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'precedence/aaa'); + + resolve('./', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg.name, 'resolve'); + }); +}); + +test('./ should not load ${dir}.js', function (t) { // eslint-disable-line no-template-curly-in-string + t.plan(1); + var dir = path.join(__dirname, 'precedence/bbb'); + + resolve('./', { basedir: dir }, function (err, res, pkg) { + t.ok(err); + }); +}); diff --git a/node_modules/resolve/test/precedence/aaa.js b/node_modules/resolve/test/precedence/aaa.js new file mode 100644 index 0000000..b83a3e7 --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa.js @@ -0,0 +1 @@ +module.exports = 'wtf'; diff --git a/node_modules/resolve/test/precedence/aaa/index.js b/node_modules/resolve/test/precedence/aaa/index.js new file mode 100644 index 0000000..e0f8f6a --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'okok'; diff --git a/node_modules/resolve/test/precedence/aaa/main.js b/node_modules/resolve/test/precedence/aaa/main.js new file mode 100644 index 0000000..93542a9 --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa/main.js @@ -0,0 +1 @@ +console.log(require('./')); diff --git a/node_modules/resolve/test/precedence/bbb.js b/node_modules/resolve/test/precedence/bbb.js new file mode 100644 index 0000000..2298f47 --- /dev/null +++ b/node_modules/resolve/test/precedence/bbb.js @@ -0,0 +1 @@ +module.exports = '>_<'; diff --git a/node_modules/resolve/test/precedence/bbb/main.js b/node_modules/resolve/test/precedence/bbb/main.js new file mode 100644 index 0000000..716b81d --- /dev/null +++ b/node_modules/resolve/test/precedence/bbb/main.js @@ -0,0 +1 @@ +console.log(require('./')); // should throw diff --git a/node_modules/resolve/test/resolver.js b/node_modules/resolve/test/resolver.js new file mode 100644 index 0000000..4903165 --- /dev/null +++ b/node_modules/resolve/test/resolver.js @@ -0,0 +1,595 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); +var async = require('../async'); + +test('`./async` entry point', function (t) { + t.equal(resolve, async, '`./async` entry point is the same as `main`'); + t.end(); +}); + +test('async foo', function (t) { + t.plan(12); + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo.js', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.main, 'resolver'); + }); + + resolve('./foo.js', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg.main, 'resolver'); + }); + + resolve('./foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + }); + + resolve('foo', { basedir: dir }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.join(dir, 'baz.js') + "'"); + }); +}); + +test('bar', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'resolver'); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar', 'package': { main: 'bar' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg.main, 'bar'); + }); +}); + +test('baz', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + + resolve('./baz', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); + + resolve('./baz', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); +}); + +test('biz', function (t) { + t.plan(24); + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + resolve('./grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('./grux', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'biz'); + }); + + resolve('./garply', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('./garply', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('tiv', { basedir: dir + '/grux' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/grux', 'package': { main: 'grux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, 'grux'); + }); + + resolve('tiv', { basedir: dir + '/garply' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/garply', 'package': { main: './lib' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('grux', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('grux', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'tiv'); + }); + + resolve('garply', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('garply', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); +}); + +test('quux', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/quux'); + + resolve('./foo', { basedir: dir, 'package': { main: 'quux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo/index.js')); + t.equal(pkg.main, 'quux'); + }); +}); + +test('normalize', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + resolve('../grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg, undefined); + }); +}); + +test('cup', function (t) { + t.plan(5); + var dir = path.join(__dirname, 'resolver'); + + resolve('./cup', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup.coffee', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup', { basedir: dir, extensions: ['.js'] }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('./cup', { basedir: dir, extensions: ['.js'], filename: path.join(dir, 'cupboard.js') }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.join(dir, 'cupboard.js') + "'"); + }); +}); + +test('mug', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'resolver'); + + resolve('./mug', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'mug.js')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.coffee', '.js'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, '/mug.coffee')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + t.equal(res, path.join(dir, '/mug.js')); + }); +}); + +test('other path', function (t) { + t.plan(6); + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + resolve('root', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/root.js')); + }); + + resolve('lib/other-lib', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/lib/other-lib.js')); + }); + + resolve('root', { basedir: dir }, function (err, res) { + t.equal(err.message, "Cannot find module 'root' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('zzz', { basedir: dir, paths: [otherDir] }, function (err, res) { + t.equal(err.message, "Cannot find module 'zzz' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('path iterator', function (t) { + t.plan(2); + + var resolverDir = path.join(__dirname, 'resolver'); + + var exactIterator = function (x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + }; + + resolve('baz', { packageIterator: exactIterator }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'baz/quux.js')); + t.equal(pkg && pkg.name, 'baz'); + }); +}); + +test('incorrect main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + resolve('./incorrect_main', { basedir: resolverDir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('missing index', function (t) { + t.plan(2); + + var resolverDir = path.join(__dirname, 'resolver'); + resolve('./missing_index', { basedir: resolverDir }, function (err, res, pkg) { + t.ok(err instanceof Error); + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + }); +}); + +test('missing main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + + resolve('./missing_main', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + }); +}); + +test('null main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + + resolve('./null_main', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + }); +}); + +test('main: false', function (t) { + t.plan(2); + + var basedir = path.join(__dirname, 'resolver'); + var dir = path.join(basedir, 'false_main'); + resolve('./false_main', { basedir: basedir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal( + res, + path.join(dir, 'index.js'), + '`"main": false`: resolves to `index.js`' + ); + t.deepEqual(pkg, { + name: 'false_main', + main: false + }); + }); +}); + +test('without basedir', function (t) { + t.plan(1); + + var dir = path.join(__dirname, 'resolver/without_basedir'); + var tester = require(path.join(dir, 'main.js')); // eslint-disable-line global-require + + tester(t, function (err, res, pkg) { + if (err) { + t.fail(err); + } else { + t.equal(res, path.join(dir, 'node_modules/mymodule.js')); + } + }); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo.js')); + }); + + resolve('./foo/', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); + + resolve('.', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('async: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.plan(1); + resolve('./' + testFile, function (err, res, pkg) { + if (err) t.fail(err); + st.equal(res, __filename, 'sanity check'); + }); + }); + + t.test('with a fake directory', function (st) { + st.plan(4); + + resolve('./' + testFile + '/blah', function (err, res, pkg) { + st.ok(err, 'there is an error'); + st.notOk(res, 'no result'); + + st.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + err && err.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + st.end(); + }); + }); + + t.end(); +}); + +test('async dot main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('async dot slash main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_slash_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_slash_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('not a directory', function (t) { + t.plan(6); + var path = './foo'; + resolve(path, { basedir: __filename }, function (err, res, pkg) { + t.ok(err, 'a non-directory errors'); + t.equal(arguments.length, 1); + t.equal(res, undefined); + t.equal(pkg, undefined); + + t.equal(err && err.message, 'Cannot find module \'' + path + '\' from \'' + __filename + '\''); + t.equal(err && err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('browser field in package.json', function (t) { + t.plan(3); + + var dir = path.join(__dirname, 'resolver'); + resolve( + './browser_field', + { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }, + function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.equal(pkg && pkg.main, 'b'); + t.equal(pkg && pkg.browser, undefined); + } + ); +}); + +test('absolute paths', function (t) { + t.plan(4); + + var extensionless = __filename.slice(0, -path.extname(__filename).length); + + resolve(__filename, function (err, res) { + t.equal( + res, + __filename, + 'absolute path to this file resolves' + ); + }); + resolve(extensionless, function (err, res) { + t.equal( + res, + __filename, + 'extensionless absolute path to this file resolves' + ); + }); + resolve(__filename, { basedir: process.cwd() }, function (err, res) { + t.equal( + res, + __filename, + 'absolute path to this file with a basedir resolves' + ); + }); + resolve(extensionless, { basedir: process.cwd() }, function (err, res) { + t.equal( + res, + __filename, + 'extensionless absolute path to this file with a basedir resolves' + ); + }); +}); + +test('malformed package.json', function (t) { + /* eslint operator-linebreak: ["error", "before"], function-paren-newline: "off" */ + t.plan( + (3 * 3) // 3 sets of 3 assertions in the final callback + + 2 // 1 readPackage call with malformed package.json + ); + + var basedir = path.join(__dirname, 'resolver/malformed_package_json'); + var expected = path.join(basedir, 'index.js'); + + resolve('./index.js', { basedir: basedir }, function (err, res, pkg) { + t.error(err, 'no error'); + t.equal(res, expected, 'malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'malformed package.json gives an undefined `pkg` argument'); + }); + + resolve( + './index.js', + { + basedir: basedir, + packageFilter: function (pkg, pkgfile, dir) { + t.fail('should not reach here'); + } + }, + function (err, res, pkg) { + t.error(err, 'with packageFilter: no error'); + t.equal(res, expected, 'with packageFilter: malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'with packageFilter: malformed package.json gives an undefined `pkg` argument'); + } + ); + + resolve( + './index.js', + { + basedir: basedir, + readPackage: function (readFile, pkgfile, cb) { + t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path'); + readFile(pkgfile, function (err, result) { + try { + cb(null, JSON.parse(result)); + } catch (e) { + t.ok(e instanceof SyntaxError, 'readPackage: malformed package.json parses as a syntax error'); + cb(null); + } + }); + } + }, + function (err, res, pkg) { + t.error(err, 'with readPackage: no error'); + t.equal(res, expected, 'with readPackage: malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'with readPackage: malformed package.json gives an undefined `pkg` argument'); + } + ); +}); diff --git a/node_modules/resolve/test/resolver/baz/doom.js b/node_modules/resolve/test/resolver/baz/doom.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/baz/package.json b/node_modules/resolve/test/resolver/baz/package.json new file mode 100644 index 0000000..2f77720 --- /dev/null +++ b/node_modules/resolve/test/resolver/baz/package.json @@ -0,0 +1,4 @@ +{ + "name": "baz", + "main": "quux.js" +} diff --git a/node_modules/resolve/test/resolver/baz/quux.js b/node_modules/resolve/test/resolver/baz/quux.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/baz/quux.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/browser_field/a.js b/node_modules/resolve/test/resolver/browser_field/a.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/browser_field/b.js b/node_modules/resolve/test/resolver/browser_field/b.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/browser_field/package.json b/node_modules/resolve/test/resolver/browser_field/package.json new file mode 100644 index 0000000..bf406f0 --- /dev/null +++ b/node_modules/resolve/test/resolver/browser_field/package.json @@ -0,0 +1,5 @@ +{ + "name": "browser_field", + "main": "a", + "browser": "b" +} diff --git a/node_modules/resolve/test/resolver/cup.coffee b/node_modules/resolve/test/resolver/cup.coffee new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/node_modules/resolve/test/resolver/cup.coffee @@ -0,0 +1 @@ + diff --git a/node_modules/resolve/test/resolver/dot_main/index.js b/node_modules/resolve/test/resolver/dot_main/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_main/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/dot_main/package.json b/node_modules/resolve/test/resolver/dot_main/package.json new file mode 100644 index 0000000..d7f4fc8 --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "." +} diff --git a/node_modules/resolve/test/resolver/dot_slash_main/index.js b/node_modules/resolve/test/resolver/dot_slash_main/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_slash_main/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/dot_slash_main/package.json b/node_modules/resolve/test/resolver/dot_slash_main/package.json new file mode 100644 index 0000000..f51287b --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_slash_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "./" +} diff --git a/node_modules/resolve/test/resolver/false_main/index.js b/node_modules/resolve/test/resolver/false_main/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/false_main/package.json b/node_modules/resolve/test/resolver/false_main/package.json new file mode 100644 index 0000000..a7416c0 --- /dev/null +++ b/node_modules/resolve/test/resolver/false_main/package.json @@ -0,0 +1,4 @@ +{ + "name": "false_main", + "main": false +} diff --git a/node_modules/resolve/test/resolver/foo.js b/node_modules/resolve/test/resolver/foo.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/foo.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/incorrect_main/index.js b/node_modules/resolve/test/resolver/incorrect_main/index.js new file mode 100644 index 0000000..bc1fb0a --- /dev/null +++ b/node_modules/resolve/test/resolver/incorrect_main/index.js @@ -0,0 +1,2 @@ +// this is the actual main file 'index.js', not 'wrong.js' like the package.json would indicate +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/incorrect_main/package.json b/node_modules/resolve/test/resolver/incorrect_main/package.json new file mode 100644 index 0000000..b718804 --- /dev/null +++ b/node_modules/resolve/test/resolver/incorrect_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "wrong.js" +} diff --git a/node_modules/resolve/test/resolver/invalid_main/package.json b/node_modules/resolve/test/resolver/invalid_main/package.json new file mode 100644 index 0000000..0590748 --- /dev/null +++ b/node_modules/resolve/test/resolver/invalid_main/package.json @@ -0,0 +1,7 @@ +{ + "name": "invalid_main", + "main": [ + "why is this a thing", + "srsly omg wtf" + ] +} diff --git a/node_modules/resolve/test/resolver/malformed_package_json/index.js b/node_modules/resolve/test/resolver/malformed_package_json/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/malformed_package_json/package.json b/node_modules/resolve/test/resolver/malformed_package_json/package.json new file mode 100644 index 0000000..98232c6 --- /dev/null +++ b/node_modules/resolve/test/resolver/malformed_package_json/package.json @@ -0,0 +1 @@ +{ diff --git a/node_modules/resolve/test/resolver/mug.coffee b/node_modules/resolve/test/resolver/mug.coffee new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/mug.js b/node_modules/resolve/test/resolver/mug.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/multirepo/lerna.json b/node_modules/resolve/test/resolver/multirepo/lerna.json new file mode 100644 index 0000000..d6707ca --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/lerna.json @@ -0,0 +1,6 @@ +{ + "packages": [ + "packages/*" + ], + "version": "0.0.0" +} diff --git a/node_modules/resolve/test/resolver/multirepo/package.json b/node_modules/resolve/test/resolver/multirepo/package.json new file mode 100644 index 0000000..8508f9d --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/package.json @@ -0,0 +1,20 @@ +{ + "name": "monorepo-symlink-test", + "private": true, + "version": "0.0.0", + "description": "", + "main": "index.js", + "scripts": { + "postinstall": "lerna bootstrap", + "test": "node packages/package-a" + }, + "author": "", + "license": "MIT", + "dependencies": { + "jquery": "^3.3.1", + "resolve": "../../../" + }, + "devDependencies": { + "lerna": "^3.4.3" + } +} diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js b/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js new file mode 100644 index 0000000..8875a32 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var assert = require('assert'); +var path = require('path'); +var resolve = require('resolve'); + +var basedir = __dirname + '/node_modules/@my-scope/package-b'; + +var expected = path.join(__dirname, '../../node_modules/jquery/dist/jquery.js'); + +/* + * preserveSymlinks === false + * will search NPM package from + * - packages/package-b/node_modules + * - packages/node_modules + * - node_modules + */ +assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: false }), expected); +assert.equal(resolve.sync('../../node_modules/jquery', { basedir: basedir, preserveSymlinks: false }), expected); + +/* + * preserveSymlinks === true + * will search NPM package from + * - packages/package-a/node_modules/@my-scope/packages/package-b/node_modules + * - packages/package-a/node_modules/@my-scope/packages/node_modules + * - packages/package-a/node_modules/@my-scope/node_modules + * - packages/package-a/node_modules/node_modules + * - packages/package-a/node_modules + * - packages/node_modules + * - node_modules + */ +assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: true }), expected); +assert.equal(resolve.sync('../../../../../node_modules/jquery', { basedir: basedir, preserveSymlinks: true }), expected); + +console.log(' * all monorepo paths successfully resolved through symlinks'); diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json b/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json new file mode 100644 index 0000000..204de51 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json @@ -0,0 +1,14 @@ +{ + "name": "@my-scope/package-a", + "version": "0.0.0", + "private": true, + "description": "", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "echo \"Error: run tests from root\" && exit 1" + }, + "dependencies": { + "@my-scope/package-b": "^0.0.0" + } +} diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-b/index.js b/node_modules/resolve/test/resolver/multirepo/packages/package-b/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json b/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json new file mode 100644 index 0000000..f57c3b5 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json @@ -0,0 +1,14 @@ +{ + "name": "@my-scope/package-b", + "private": true, + "version": "0.0.0", + "description": "", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "echo \"Error: run tests from root\" && exit 1" + }, + "dependencies": { + "@my-scope/package-a": "^0.0.0" + } +} diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js b/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js new file mode 100644 index 0000000..9b4846a --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js @@ -0,0 +1,26 @@ +var a = require.resolve('buffer/').replace(process.cwd(), '$CWD'); +var b; +var c; + +var test = function test() { + console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false')); + console.log(b, ': preserveSymlinks true'); + console.log(c, ': preserveSymlinks false'); + + if (a !== b && a !== c) { + throw 'async: no match'; + } + console.log('async: success! a matched either b or c\n'); +}; + +require('resolve')('buffer/', { preserveSymlinks: true }, function (err, result) { + if (err) { throw err; } + b = result.replace(process.cwd(), '$CWD'); + if (b && c) { test(); } +}); +require('resolve')('buffer/', { preserveSymlinks: false }, function (err, result) { + if (err) { throw err; } + c = result.replace(process.cwd(), '$CWD'); + if (b && c) { test(); } +}); + diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json b/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json new file mode 100644 index 0000000..acfe9e9 --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json @@ -0,0 +1,15 @@ +{ + "name": "mylib", + "version": "0.0.0", + "description": "", + "private": true, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "buffer": "*" + } +} diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js b/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js new file mode 100644 index 0000000..3283efc --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js @@ -0,0 +1,12 @@ +var a = require.resolve('buffer/').replace(process.cwd(), '$CWD'); +var b = require('resolve').sync('buffer/', { preserveSymlinks: true }).replace(process.cwd(), '$CWD'); +var c = require('resolve').sync('buffer/', { preserveSymlinks: false }).replace(process.cwd(), '$CWD'); + +console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false')); +console.log(b, ': preserveSymlinks true'); +console.log(c, ': preserveSymlinks false'); + +if (a !== b && a !== c) { + throw 'sync: no match'; +} +console.log('sync: success! a matched either b or c\n'); diff --git a/node_modules/resolve/test/resolver/other_path/lib/other-lib.js b/node_modules/resolve/test/resolver/other_path/lib/other-lib.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/other_path/root.js b/node_modules/resolve/test/resolver/other_path/root.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/quux/foo/index.js b/node_modules/resolve/test/resolver/quux/foo/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/quux/foo/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/same_names/foo.js b/node_modules/resolve/test/resolver/same_names/foo.js new file mode 100644 index 0000000..888cae3 --- /dev/null +++ b/node_modules/resolve/test/resolver/same_names/foo.js @@ -0,0 +1 @@ +module.exports = 42; diff --git a/node_modules/resolve/test/resolver/same_names/foo/index.js b/node_modules/resolve/test/resolver/same_names/foo/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/same_names/foo/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/symlinked/_/node_modules/foo.js b/node_modules/resolve/test/resolver/symlinked/_/node_modules/foo.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/symlinked/_/symlink_target/.gitkeep b/node_modules/resolve/test/resolver/symlinked/_/symlink_target/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/symlinked/package/bar.js b/node_modules/resolve/test/resolver/symlinked/package/bar.js new file mode 100644 index 0000000..cb1c2c0 --- /dev/null +++ b/node_modules/resolve/test/resolver/symlinked/package/bar.js @@ -0,0 +1 @@ +module.exports = 'bar'; diff --git a/node_modules/resolve/test/resolver/symlinked/package/package.json b/node_modules/resolve/test/resolver/symlinked/package/package.json new file mode 100644 index 0000000..8e1b585 --- /dev/null +++ b/node_modules/resolve/test/resolver/symlinked/package/package.json @@ -0,0 +1,3 @@ +{ + "main": "bar.js" +} \ No newline at end of file diff --git a/node_modules/resolve/test/resolver/without_basedir/main.js b/node_modules/resolve/test/resolver/without_basedir/main.js new file mode 100644 index 0000000..5b31975 --- /dev/null +++ b/node_modules/resolve/test/resolver/without_basedir/main.js @@ -0,0 +1,5 @@ +var resolve = require('../../../'); + +module.exports = function (t, cb) { + resolve('mymodule', null, cb); +}; diff --git a/node_modules/resolve/test/resolver_sync.js b/node_modules/resolve/test/resolver_sync.js new file mode 100644 index 0000000..53453d6 --- /dev/null +++ b/node_modules/resolve/test/resolver_sync.js @@ -0,0 +1,726 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); + +var resolve = require('../'); +var sync = require('../sync'); + +var requireResolveSupportsPaths = require.resolve.length > 1 + && !(/^v12\.[012]\./).test(process.version); // broken in v12.0-12.2, see https://github.com/nodejs/node/issues/27794 + +test('`./sync` entry point', function (t) { + t.equal(resolve.sync, sync, '`./sync` entry point is the same as `.sync` on `main`'); + t.end(); +}); + +test('foo', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./foo', { basedir: dir }), + path.join(dir, 'foo.js'), + './foo' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo', { basedir: dir }), + require.resolve('./foo', { paths: [dir] }), + './foo: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + path.join(dir, 'foo.js'), + './foo.js' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + require.resolve('./foo.js', { paths: [dir] }), + './foo.js: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo.js', { basedir: dir, filename: path.join(dir, 'bar.js') }), + path.join(dir, 'foo.js') + ); + + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }); + + // Test that filename is reported as the "from" value when passed. + t.throws( + function () { + resolve.sync('foo', { basedir: dir, filename: path.join(dir, 'bar.js') }); + }, + { + name: 'Error', + message: "Cannot find module 'foo' from '" + path.join(dir, 'bar.js') + "'" + } + ); + + t.end(); +}); + +test('bar', function (t) { + var dir = path.join(__dirname, 'resolver'); + + var basedir = path.join(dir, 'bar'); + + t.equal( + resolve.sync('foo', { basedir: basedir }), + path.join(dir, 'bar/node_modules/foo/index.js'), + 'foo in bar' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('foo', { basedir: basedir }), + require.resolve('foo', { paths: [basedir] }), + 'foo in bar: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('baz', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./baz', { basedir: dir }), + path.join(dir, 'baz/quux.js'), + './baz' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./baz', { basedir: dir }), + require.resolve('./baz', { paths: [dir] }), + './baz: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('biz', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + t.equal( + resolve.sync('./grux', { basedir: dir }), + path.join(dir, 'grux/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./grux', { basedir: dir }), + require.resolve('./grux', { paths: [dir] }), + './grux: resolve.sync === require.resolve' + ); + } + + var tivDir = path.join(dir, 'grux'); + t.equal( + resolve.sync('tiv', { basedir: tivDir }), + path.join(dir, 'tiv/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('tiv', { basedir: tivDir }), + require.resolve('tiv', { paths: [tivDir] }), + 'tiv: resolve.sync === require.resolve' + ); + } + + var gruxDir = path.join(dir, 'tiv'); + t.equal( + resolve.sync('grux', { basedir: gruxDir }), + path.join(dir, 'grux/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('grux', { basedir: gruxDir }), + require.resolve('grux', { paths: [gruxDir] }), + 'grux: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('normalize', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + t.equal( + resolve.sync('../grux', { basedir: dir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('../grux', { basedir: dir }), + require.resolve('../grux', { paths: [dir] }), + '../grux: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('cup', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'cup.coffee'), + './cup -> ./cup.coffee' + ); + + t.equal( + resolve.sync('./cup.coffee', { basedir: dir }), + path.join(dir, 'cup.coffee'), + './cup.coffee' + ); + + t.throws(function () { + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js'] + }); + }); + + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./cup.coffee', { basedir: dir, extensions: ['.js', '.coffee'] }), + require.resolve('./cup.coffee', { paths: [dir] }), + './cup.coffee: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('mug', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./mug', { basedir: dir }), + path.join(dir, 'mug.js'), + './mug -> ./mug.js' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./mug', { basedir: dir }), + require.resolve('./mug', { paths: [dir] }), + './mug: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.coffee', '.js'] + }), + path.join(dir, 'mug.coffee'), + './mug -> ./mug.coffee' + ); + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'mug.js'), + './mug -> ./mug.js' + ); + + t.end(); +}); + +test('other path', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + t.equal( + resolve.sync('root', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/root.js') + ); + + t.equal( + resolve.sync('lib/other-lib', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/lib/other-lib.js') + ); + + t.throws(function () { + resolve.sync('root', { basedir: dir }); + }); + + t.throws(function () { + resolve.sync('zzz', { + basedir: dir, + paths: [otherDir] + }); + }); + + t.end(); +}); + +test('path iterator', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + var exactIterator = function (x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + }; + + t.equal( + resolve.sync('baz', { packageIterator: exactIterator }), + path.join(resolverDir, 'baz/quux.js') + ); + + t.end(); +}); + +test('incorrect main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + require.resolve('./incorrect_main', { paths: [resolverDir] }), + './incorrect_main: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('missing index', function (t) { + t.plan(requireResolveSupportsPaths ? 2 : 1); + + var resolverDir = path.join(__dirname, 'resolver'); + try { + resolve.sync('./missing_index', { basedir: resolverDir }); + t.fail('did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + if (requireResolveSupportsPaths) { + try { + require.resolve('./missing_index', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + } +}); + +test('missing main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + try { + resolve.sync('./missing_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + if (requireResolveSupportsPaths) { + try { + resolve.sync('./missing_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + } + + t.end(); +}); + +test('null main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + try { + resolve.sync('./null_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + if (requireResolveSupportsPaths) { + try { + resolve.sync('./null_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + } + + t.end(); +}); + +test('main: false', function (t) { + var basedir = path.join(__dirname, 'resolver'); + var dir = path.join(basedir, 'false_main'); + t.equal( + resolve.sync('./false_main', { basedir: basedir }), + path.join(dir, 'index.js'), + '`"main": false`: resolves to `index.js`' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./false_main', { basedir: basedir }), + require.resolve('./false_main', { paths: [basedir] }), + '`"main": false`: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +var stubStatSync = function stubStatSync(fn) { + var statSync = fs.statSync; + try { + fs.statSync = function () { + throw new EvalError('Unknown Error'); + }; + return fn(); + } finally { + fs.statSync = statSync; + } +}; + +test('#79 - re-throw non ENOENT errors from stat', function (t) { + var dir = path.join(__dirname, 'resolver'); + + stubStatSync(function () { + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }, /Unknown Error/); + }); + + t.end(); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + var basedir = path.join(dir, 'same_names'); + + t.equal( + resolve.sync('./foo', { basedir: basedir }), + path.join(dir, 'same_names/foo.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo', { basedir: basedir }), + require.resolve('./foo', { paths: [basedir] }), + './foo: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo/', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo/', { basedir: basedir }), + require.resolve('./foo/', { paths: [basedir] }), + './foo/: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + var basedir = path.join(dir, 'same_names/foo'); + + t.equal( + resolve.sync('./', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js'), + './' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./', { basedir: basedir }), + require.resolve('./', { paths: [basedir] }), + './: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('.', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js'), + '.' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('.', { basedir: basedir }), + require.resolve('.', { paths: [basedir] }), + '.: resolve.sync === require.resolve', + { todo: true } + ); + } + + t.end(); +}); + +test('sync: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.equal( + resolve.sync('./' + testFile), + __filename, + 'sanity check' + ); + st.equal( + resolve.sync('./' + testFile), + require.resolve('./' + testFile), + 'sanity check: resolve.sync === require.resolve' + ); + + st.end(); + }); + + t.test('with a fake directory', function (st) { + function run() { return resolve.sync('./' + testFile + '/blah'); } + + st.throws(run, 'throws an error'); + + try { + run(); + } catch (e) { + st.equal(e.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + e.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + } + + st.end(); + }); + + t.end(); +}); + +test('sync dot main', function (t) { + var start = new Date(); + + t.equal( + resolve.sync('./resolver/dot_main'), + path.join(__dirname, 'resolver/dot_main/index.js'), + './resolver/dot_main' + ); + t.equal( + resolve.sync('./resolver/dot_main'), + require.resolve('./resolver/dot_main'), + './resolver/dot_main: resolve.sync === require.resolve' + ); + + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + + t.end(); +}); + +test('sync dot slash main', function (t) { + var start = new Date(); + + t.equal( + resolve.sync('./resolver/dot_slash_main'), + path.join(__dirname, 'resolver/dot_slash_main/index.js') + ); + t.equal( + resolve.sync('./resolver/dot_slash_main'), + require.resolve('./resolver/dot_slash_main'), + './resolver/dot_slash_main: resolve.sync === require.resolve' + ); + + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + + t.end(); +}); + +test('not a directory', function (t) { + var path = './foo'; + try { + resolve.sync(path, { basedir: __filename }); + t.fail(); + } catch (err) { + t.ok(err, 'a non-directory errors'); + t.equal(err && err.message, 'Cannot find module \'' + path + "' from '" + __filename + "'"); + t.equal(err && err.code, 'MODULE_NOT_FOUND'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('browser field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + var res = resolve.sync('./browser_field', { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.end(); +}); + +test('absolute paths', function (t) { + var extensionless = __filename.slice(0, -path.extname(__filename).length); + + t.equal( + resolve.sync(__filename), + __filename, + 'absolute path to this file resolves' + ); + t.equal( + resolve.sync(__filename), + require.resolve(__filename), + 'absolute path to this file: resolve.sync === require.resolve' + ); + + t.equal( + resolve.sync(extensionless), + __filename, + 'extensionless absolute path to this file resolves' + ); + t.equal( + resolve.sync(__filename), + require.resolve(__filename), + 'absolute path to this file: resolve.sync === require.resolve' + ); + + t.equal( + resolve.sync(__filename, { basedir: process.cwd() }), + __filename, + 'absolute path to this file with a basedir resolves' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync(__filename, { basedir: process.cwd() }), + require.resolve(__filename, { paths: [process.cwd()] }), + 'absolute path to this file + basedir: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync(extensionless, { basedir: process.cwd() }), + __filename, + 'extensionless absolute path to this file with a basedir resolves' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync(extensionless, { basedir: process.cwd() }), + require.resolve(extensionless, { paths: [process.cwd()] }), + 'extensionless absolute path to this file + basedir: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('malformed package.json', function (t) { + t.plan(5 + (requireResolveSupportsPaths ? 1 : 0)); + + var basedir = path.join(__dirname, 'resolver/malformed_package_json'); + var expected = path.join(basedir, 'index.js'); + + t.equal( + resolve.sync('./index.js', { basedir: basedir }), + expected, + 'malformed package.json is silently ignored' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./index.js', { basedir: basedir }), + require.resolve('./index.js', { paths: [basedir] }), + 'malformed package.json: resolve.sync === require.resolve' + ); + } + + var res1 = resolve.sync( + './index.js', + { + basedir: basedir, + packageFilter: function (pkg, pkgfile, dir) { + t.fail('should not reach here'); + } + } + ); + + t.equal( + res1, + expected, + 'with packageFilter: malformed package.json is silently ignored' + ); + + var res2 = resolve.sync( + './index.js', + { + basedir: basedir, + readPackageSync: function (readFileSync, pkgfile) { + t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path'); + var result = String(readFileSync(pkgfile)); + try { + return JSON.parse(result); + } catch (e) { + t.ok(e instanceof SyntaxError, 'readPackageSync: malformed package.json parses as a syntax error'); + } + } + } + ); + + t.equal( + res2, + expected, + 'with readPackageSync: malformed package.json is silently ignored' + ); +}); diff --git a/node_modules/resolve/test/shadowed_core.js b/node_modules/resolve/test/shadowed_core.js new file mode 100644 index 0000000..3a5f4fc --- /dev/null +++ b/node_modules/resolve/test/shadowed_core.js @@ -0,0 +1,54 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('shadowed core modules still return core module', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, 'util'); + }); +}); + +test('shadowed core modules still return core module [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, 'util'); +}); + +test('shadowed core modules return shadow when appending `/`', function (t) { + t.plan(2); + + resolve('util/', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow when appending `/` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util/', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false`', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); diff --git a/node_modules/resolve/test/shadowed_core/node_modules/util/index.js b/node_modules/resolve/test/shadowed_core/node_modules/util/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/subdirs.js b/node_modules/resolve/test/subdirs.js new file mode 100644 index 0000000..b7b8450 --- /dev/null +++ b/node_modules/resolve/test/subdirs.js @@ -0,0 +1,13 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('subdirs', function (t) { + t.plan(2); + + var dir = path.join(__dirname, '/subdirs'); + resolve('a/b/c/x.json', { basedir: dir }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(dir, 'node_modules/a/b/c/x.json')); + }); +}); diff --git a/node_modules/resolve/test/symlinks.js b/node_modules/resolve/test/symlinks.js new file mode 100644 index 0000000..35f881a --- /dev/null +++ b/node_modules/resolve/test/symlinks.js @@ -0,0 +1,176 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); +var map = require('array.prototype.map'); +var resolve = require('../'); + +var symlinkDir = path.join(__dirname, 'resolver', 'symlinked', 'symlink'); +var packageDir = path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'package'); +var modADir = path.join(__dirname, 'symlinks', 'source', 'node_modules', 'mod-a'); +var symlinkModADir = path.join(__dirname, 'symlinks', 'dest', 'node_modules', 'mod-a'); +try { + fs.unlinkSync(symlinkDir); +} catch (err) {} +try { + fs.unlinkSync(packageDir); +} catch (err) {} +try { + fs.unlinkSync(modADir); +} catch (err) {} +try { + fs.unlinkSync(symlinkModADir); +} catch (err) {} + +try { + fs.symlinkSync('./_/symlink_target', symlinkDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, 'resolver', 'symlinked', '_', 'symlink_target') + '\\', symlinkDir, 'junction'); +} +try { + fs.symlinkSync('../../package', packageDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'package') + '\\', packageDir, 'junction'); +} +try { + fs.symlinkSync('../../source/node_modules/mod-a', symlinkModADir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'source', 'node_modules', 'mod-a') + '\\', symlinkModADir, 'junction'); +} + +test('symlink', function (t) { + t.plan(2); + + resolve('foo', { basedir: symlinkDir, preserveSymlinks: false }, function (err, res, pkg) { + t.error(err); + t.equal(res, path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js')); + }); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.plan(4); + + resolve('foo', { basedir: symlinkDir }, function (err, res, pkg) { + t.ok(err, 'there is an error'); + t.notOk(res, 'no result'); + + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + t.equal( + err && err.message, + 'Cannot find module \'foo\' from \'' + symlinkDir + '\'', + 'can not find nonexistent module' + ); + }); +}); + +test('sync symlink', function (t) { + var start = new Date(); + t.doesNotThrow(function () { + t.equal( + resolve.sync('foo', { basedir: symlinkDir, preserveSymlinks: false }), + path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js') + ); + }); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.throws(function () { + resolve.sync('foo', { basedir: symlinkDir }); + }, /Cannot find module 'foo'/); + t.end(); +}); + +test('sync symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + var fn = resolve.sync('package', { basedir: basedir, preserveSymlinks: false }); + + t.equal(fn, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + t.end(); +}); + +test('async symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + t.plan(2); + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + resolve('package', { basedir: basedir, preserveSymlinks: false }, function (err, result) { + t.notOk(err, 'no error'); + t.equal(result, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + }); +}); + +test('packageFilter', function (t) { + function relative(x) { + return path.relative(__dirname, x); + } + + function testPackageFilter(preserveSymlinks) { + return function (st) { + st.plan('is 1.x' ? 3 : 5); // eslint-disable-line no-constant-condition + + var destMain = 'symlinks/dest/node_modules/mod-a/index.js'; + var destPkg = 'symlinks/dest/node_modules/mod-a/package.json'; + var sourceMain = 'symlinks/source/node_modules/mod-a/index.js'; + var sourcePkg = 'symlinks/source/node_modules/mod-a/package.json'; + var destDir = path.join(__dirname, 'symlinks', 'dest'); + + /* eslint multiline-comment-style: 0 */ + /* v2.x will restore these tests + var packageFilterPath = []; + var actualPath = resolve.sync('mod-a', { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile, dir) { + packageFilterPath.push(pkgfile); + } + }); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'sync: actual path is correct' + ); + st.deepEqual( + map(packageFilterPath, relative), + map(preserveSymlinks ? [destPkg, destPkg] : [sourcePkg, sourcePkg], path.normalize), + 'sync: packageFilter pkgfile arg is correct' + ); + */ + + var asyncPackageFilterPath = []; + resolve( + 'mod-a', + { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile) { + asyncPackageFilterPath.push(pkgfile); + } + }, + function (err, actualPath) { + st.error(err, 'no error'); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'async: actual path is correct' + ); + st.deepEqual( + map(asyncPackageFilterPath, relative), + map( + preserveSymlinks ? [destPkg, destPkg, destPkg] : [sourcePkg, sourcePkg, sourcePkg], + path.normalize + ), + 'async: packageFilter pkgfile arg is correct' + ); + } + ); + }; + } + + t.test('preserveSymlinks: false', testPackageFilter(false)); + + t.test('preserveSymlinks: true', testPackageFilter(true)); + + t.end(); +}); diff --git a/node_modules/rollup/CHANGELOG.md b/node_modules/rollup/CHANGELOG.md new file mode 100644 index 0000000..23a887b --- /dev/null +++ b/node_modules/rollup/CHANGELOG.md @@ -0,0 +1,6762 @@ +# rollup changelog + +## 2.79.1 + +_2022-09-22_ + +### Bug Fixes + +- Avoid massive performance degradation when creating thousands of chunks (#4643) + +### Pull Requests + +- [#4639](https://github.com/rollup/rollup/pull/4639): fix: typo docs and contributors link in CONTRIBUTING.md (@takurinton) +- [#4641](https://github.com/rollup/rollup/pull/4641): Update type definition of resolveId (@ivanjonas) +- [#4643](https://github.com/rollup/rollup/pull/4643): Improve performance of chunk naming collision check (@lukastaegert) + +## 2.79.0 + +_2022-08-31_ + +### Features + +- Add `amd.forceJsExtensionForImports` to enforce using `.js` extensions for relative AMD imports (#4607) + +### Pull Requests + +- [#4607](https://github.com/rollup/rollup/pull/4607): add option to keep extensions for amd (@wh1tevs) + +## 2.78.1 + +_2022-08-19_ + +### Bug Fixes + +- Avoid inferring "arguments" as name for a default export placeholder variable (#4613) + +### Pull Requests + +- [#4613](https://github.com/rollup/rollup/pull/4613): Prevent using arguments for generated variable names (@lukastaegert) + +## 2.78.0 + +_2022-08-14_ + +### Features + +- Support writing plugin hooks as objects with a "handler" property (#4600) +- Allow changing execution order per plugin hook (#4600) +- Add flag to execute plugins in async parallel hooks sequentially (#4600) + +### Pull Requests + +- [#4600](https://github.com/rollup/rollup/pull/4600): Allow using objects as hooks to change execution order (@lukastaegert) + +## 2.77.3 + +_2022-08-11_ + +### Bug Fixes + +- Correctly resolve preserveModulesRoot in Vite (#4591) + +### Pull Requests + +- [#4591](https://github.com/rollup/rollup/pull/4591): resolve currentPath (@cleverpp) + +## 2.77.2 + +_2022-07-27_ + +### Bug Fixes + +- Avoid a rendering failure when mixing outputs with inlined and non-inlined dynamic imports (#4589) + +### Pull Requests + +- [#4589](https://github.com/rollup/rollup/pull/4589): Handle generating non-inlined imports after inlined ones (@lukastaegert) + +## 2.77.1 + +_2022-07-26_ + +### Bug Fixes + +- Ensure IIFE output generates a global variable when generating ES5 (#4588) + +### Pull Requests + +- [#4577](https://github.com/rollup/rollup/pull/4577): broken link removed (@Jawad-H) +- [#4580](https://github.com/rollup/rollup/pull/4580): Update dependencies (@lukastaegert) +- [#4584](https://github.com/rollup/rollup/pull/4584): Documentation clarity and syntax improvements (@berniegp) +- [#4588](https://github.com/rollup/rollup/pull/4588): Use var for IIFE (@lukastaegert) + +## 2.77.0 + +_2022-07-15_ + +### Features + +- Introduce `maxParallelFileOps` to limit both read and write operations, default to 20 and replaces `maxParallelFileRead` (#4570) + +### Bug Fixes + +- Avoid including variables referenced from return statements that are never reached (#4573) + +### Pull Requests + +- [#4570](https://github.com/rollup/rollup/pull/4570): Introduce maxParallelFileOps to limit parallel writes (@lukastaegert) +- [#4572](https://github.com/rollup/rollup/pull/4572): Document more ways to read package.json in ESM (@berniegp) +- [#4573](https://github.com/rollup/rollup/pull/4573): Do not include unused return expressions (@lukastaegert) + +## 2.76.0 + +_2022-07-08_ + +### Features + +- Allow setting a `sourcmapBaseUrl` for absolute paths in sourcemaps (#4527) + +### Bug Fixes + +- Support absolute CLI plugin paths on Windows (#4533) + +### Pull Requests + +- [#4527](https://github.com/rollup/rollup/pull/4527): Add sourcemapBaseUrl option (@nickgarlis) +- [#4533](https://github.com/rollup/rollup/pull/4533): Add support for absolute plugin paths (@ygoe) +- [#4538](https://github.com/rollup/rollup/pull/4538): chore: Included githubactions in the dependabot config (@naveensrinivasan) +- [#4546](https://github.com/rollup/rollup/pull/4546): Adapt Node versions on CI to prepare for v3 (@lukastaegert) +- [#4556](https://github.com/rollup/rollup/pull/4556): Improve error message for invalid patterns (@DysphoricUnicorn) +- [#4559](https://github.com/rollup/rollup/pull/4559): Update dependencies (@lukastaegert) +- [#4560](https://github.com/rollup/rollup/pull/4560): Bump peter-evans/create-or-update-comment from 1 to 2 (@dependabot) +- [#4561](https://github.com/rollup/rollup/pull/4561): Bump peter-evans/find-comment from 1 to 2 (@dependabot) +- [#4562](https://github.com/rollup/rollup/pull/4562): Bump codecov/codecov-action from 1 to 3 (@dependabot) + +## 2.75.7 + +_2022-06-20_ + +### Bug Fixes + +- Mark Array.prototype.group/groupToMap as side effect free. (#4531) + +### Pull Requests + +- [#4523](https://github.com/rollup/rollup/pull/4523): chore: remove source map workaround, bump deps (@dnalborczyk) +- [#4525](https://github.com/rollup/rollup/pull/4525): Add regression tests for instanceof (@lukastaegert) +- [#4528](https://github.com/rollup/rollup/pull/4528): chore: Set permissions for GitHub actions (@naveensrinivasan) +- [#4531](https://github.com/rollup/rollup/pull/4531): fix: rename Array.prototype.group/groupToMap (@dnalborczyk) +- [#4535](https://github.com/rollup/rollup/pull/4535): chore: bump resolve from 1.22.0 to 1.22.1 (@pos777) + +## 2.75.6 + +_2022-06-07_ + +### Bug Fixes + +- Properly deoptimize "this" when using member expressions with getters/setters in for loops and update expressions (#4522) + +### Pull Requests + +- [#4522](https://github.com/rollup/rollup/pull/4522): Refactor side effect handling for property interactions (@lukastaegert) + +## 2.75.5 + +_2022-06-01_ + +### Bug Fixes + +- Avoid crashes when using logical expressions for unused constructor arguments (#4519) +- Fix missing parameter defaults for calls from try statements and functions returned by functions (#4520) + +### Pull Requests + +- [#4519](https://github.com/rollup/rollup/pull/4519): Try to make logical expression deoptimization more robust (@lukastaegert) +- [#4520](https://github.com/rollup/rollup/pull/4520): Roll back parameter default tree shaking (@lukastaegert) + +## 2.75.4 + +_2022-05-31_ + +### Bug Fixes + +- Ensure parameter defaults are retained when a function is used as an object property (#4516) + +### Pull Requests + +- [#4516](https://github.com/rollup/rollup/pull/4516): Deoptimize parameter defaults when referenced from object/array/class literals (@lukastaegert) + +## 2.75.3 + +_2022-05-29_ + +### Bug Fixes + +- Retain parameter defaults for functions that are defaults themselves (#4515) +- Track mutations for objects as default values (#4515) + +### Pull Requests + +- [#4515](https://github.com/rollup/rollup/pull/4515): Ensure parameter defaults are deoptimized (@lukastaegert) + +## 2.75.1 + +_2022-05-28_ + +### Pull Requests + +- [#4513](https://github.com/rollup/rollup/pull/4513): Update link to node polyfill repo (@lukastaegert) + +## 2.75.0 + +_2022-05-27_ + +### Features + +- Re-implement default parameter tree-shaking for top-level functions (#4510) +- Do not consider calling string methods like `.trim()` on template literals a side effect (#4511) + +### Pull Requests + +- [#4510](https://github.com/rollup/rollup/pull/4510): Tree-shake parameter defaults (replaces #4498) (@lukastaegert) +- [#4511](https://github.com/rollup/rollup/pull/4511): Tree-shake side-effect-free string methods on template literals (@lukastaegert) + +## 2.74.1 + +_2022-05-19_ + +### Bug Fixes + +- Revert #4498 until some issues are understood and resolved + +## 2.74.0 + +_2022-05-19_ + +### Features + +- Remove unneeded default values for function parameters (#4498) + +### Bug Fixes + +- Use a consistent mechanism to resolve the config file to avoid issues on Windows (#4501) +- Avoid an inaccurate warning about an event emitter leak for complicated builds (#4502) +- Ensure that reexporting values from other chunks via dynamic imports does not reference non-imported variables (#4499) + +### Pull Requests + +- [#4498](https://github.com/rollup/rollup/pull/4498): Tree shake parameter defaults (@lukastaegert) +- [#4499](https://github.com/rollup/rollup/pull/4499): Ensure reexports are available for namespaces (@lukastaegert) +- [#4501](https://github.com/rollup/rollup/pull/4501): fix: config path problem on windows (@pos777) +- [#4502](https://github.com/rollup/rollup/pull/4502): Avoid maximum listeners exceeded warning (@lukastaegert) + +## 2.73.0 + +_2022-05-13_ + +### Features + +- Do not treat Object.defineProperty/ies as side effect when called on an unused object (#4493) +- Do not assume that assigning a property can create a getter with side effects (#4493) +- Do not treat string.prototype.replace(All) as side effect when used with two literals (#4493) + +### Bug Fixes + +- Detect side effects when manually declaring getters on functions (#4493) + +### Pull Requests + +- [#4493](https://github.com/rollup/rollup/pull/4493): Handle getters on functions and improve property deoptimization (@lukastaegert) +- [#4494](https://github.com/rollup/rollup/pull/4494): Do not treat string.replace as side effect when used with a literal (@lukastaegert) +- [#4495](https://github.com/rollup/rollup/pull/4495): Update docs for --configPlugin using typescript (@Jimmydalecleveland) + +## 2.72.1 + +_2022-05-07_ + +### Bug Fixes + +- Improve tree-shaking of classes with super classes in certain scenarios (#4489) + +### Pull Requests + +- [#4489](https://github.com/rollup/rollup/pull/4489): Do not deoptimize entire super class when adding a property (@lukastaegert) + +## 2.72.0 + +_2022-05-05_ + +### Features + +- Add CLI hooks to run external commands at certain points in watch mode (#4457) + +### Bug Fixes + +- Fix an issue that could accidentally treat relevant assignments as side effect free (#4486) + +### Pull Requests + +- [#4457](https://github.com/rollup/rollup/pull/4457): feat: CLI event hook flags (@Harris-Miller) +- [#4486](https://github.com/rollup/rollup/pull/4486): Fix reassignment tracking (@lukastaegert) + +## 2.71.1 + +_2022-04-30_ + +### Bug Fixes + +- Allow importing loadConfigFile without extension (#4483) + +### Pull Requests + +- [#4483](https://github.com/rollup/rollup/pull/4483): Add exports exception for loadConfigFile (@lukastaegert) + +## 2.71.0 + +_2022-04-30_ + +## Features + +- Mark `Object.hasOwn` as pure (#4482) + +### Bug Fixes + +- Prevent infinite recursion and display proper warning for recursive reexports (#4472) +- Fix type issue in TypeScript nightly (#4471) + +### Pull Requests + +- [#4467](https://github.com/rollup/rollup/pull/4467): docs: update deprecated option in tools.md (@kimjh96) +- [#4471](https://github.com/rollup/rollup/pull/4471): Fix: tsc did not build (@frank-dspeed) +- [#4472](https://github.com/rollup/rollup/pull/4472): Throw proper error when indirectly reexporting a recursive binding (@lukastaegert) +- [#4475](https://github.com/rollup/rollup/pull/4475): chore: bump deps (#4475) (@dnalborczyk) +- [#4477](https://github.com/rollup/rollup/pull/4477): chore: bump github actions (@dnalborczyk) +- [#4478](https://github.com/rollup/rollup/pull/4478): ci: test with node.js v18, remove v17 (@dnalborczyk) +- [#4479](https://github.com/rollup/rollup/pull/4479): chore(repo): replace `git.io` in the issue template (@SukkaW) +- [#4482](https://github.com/rollup/rollup/pull/4482): feat: add Object.hasOwn as pure function (@dnalborczyk) + +## 2.70.2 + +_2022-04-15_ + +### Bug Fixes + +- Do not enforce undefined return values in TypeScript types (#4463) + +### Pull Requests + +- [#4463](https://github.com/rollup/rollup/pull/4463): use void for options hook instead of undefined (@ycmjason) + +## 2.70.1 + +_2022-03-14_ + +### Bug Fixes + +- Handle unfinished hook action errors as regular errors and avoid console logging (#4434) +- Allow access to "dist" folder in a Node 17 compatible way (#4436) + +### Pull Requests + +- [#4434](https://github.com/rollup/rollup/pull/4434): Track unfinished hook actions as regular errors (@lukastaegert) +- [#4436](https://github.com/rollup/rollup/pull/4436): Update package.json (@frank-dspeed) + +## 2.70.0 + +_2022-03-07_ + +### Features + +- Make the `watchChange` and `closeWatcher` hooks asynchronous and make Rollup wait for these hooks before continuing (#4427) + +### Bug Fixes + +- Do not abort watch mode for errors in `watchChange` but display them properly (#4427) + +### Pull Requests + +- [#4427](https://github.com/rollup/rollup/pull/4427): Do not abort watch mode on errors in watchChange (@lukastaegert) + +## 2.69.2 + +_2022-03-06_ + +### Bug Fixes + +- Mark `Object.entries` and `Object.fromEntries` as pure (#4429) +- Make sure new properties on Array.prototype and Object.prototype are not evaluated as "undefined" (#4428) + +### Pull Requests + +- [#4428](https://github.com/rollup/rollup/pull/4428): Treat unknown prototype props as unknown (@lukastaegert) +- [#4429](https://github.com/rollup/rollup/pull/4429): Treat unknown prototype props as unknown (@869288142) + +## 2.69.1 + +_2022-03-04_ + +### Bug Fixes + +- Approximate source position instead of ignoring it when using a low-resolution source map in a transform hook (#4334) + +### Pull Requests + +- [#4334](https://github.com/rollup/rollup/pull/4334): fix(sourcemap): fall back to low-resolution line mapping (@aleclarson and @lukastaegert) + +## 2.69.0 + +_2022-03-02_ + +### Features + +- Introduce new `output.generatedCode.symbols` to control the usage of Symbols in Rollup-generated code (#4378) +- soft-deprecate `output.namespaceToStringTag` in favor of `output.generatedCode.symbols` (#4378) + +### Bug Fixes + +- Properly handle `./` and `../` as external dependencies (#4419) +- Make generated "Module" namespace toStringTag non-enumerable for correct Object.assign/spread behaviour (#4378) +- Add file name to error when top-level-await is used in disallowed formats (#4421) + +### Pull Requests + +- [#4378](https://github.com/rollup/rollup/pull/4378): Make namespace @@toStringTag "Module" non-enumerable (@dnalborczyk and @lukastaegert) +- [#4413](https://github.com/rollup/rollup/pull/4413): refactor: some code and type fixes (@dnalborczyk) +- [#4418](https://github.com/rollup/rollup/pull/4418): chore: bump deps (@dnalborczyk) +- [#4419](https://github.com/rollup/rollup/pull/4419): Properly handle upper directories as external dependencies (@lukastaegert) +- [#4421](https://github.com/rollup/rollup/pull/4421): Improve the error prompt and output the error file name (@caoxiemeihao) +- [#4423](https://github.com/rollup/rollup/pull/4423): Update 999-big-list-of-options.md (@leoj3n) + +## 2.68.0 + +_2022-02-22_ + +### Features + +- provide information about cached import resolutions in `shouldTransformCachedModule` (#4414) +- Add "types" field to Rollup's package exports (#4416) + +### Pull Requests + +- [#4410](https://github.com/rollup/rollup/pull/4410): refactor: use map for declarations and name suggestions (@dnalborczyk) +- [#4411](https://github.com/rollup/rollup/pull/4411): refactor: use map for namespace reexports by name (@dnalborczyk) +- [#4412](https://github.com/rollup/rollup/pull/4412): refactor: use includes where appropriate (@dnalborczyk) +- [#4414](https://github.com/rollup/rollup/pull/4414): Add resolved sources to shouldTransformCachedModule (@lukastaegert) +- [#4416](https://github.com/rollup/rollup/pull/4416): Add Typescript 4.5 nodenext node12 module resolution support (@frank-dspeed) + +## 2.67.3 + +_2022-02-18_ + +### Bug Fixes + +- Do not swallow other errors when unfinished hook actions are detected (#4409) +- Add additional information to output when there are unfinished hook actions (#4409) + +### Pull Requests + +- [#4399](https://github.com/rollup/rollup/pull/4399): docs: remove const (@TrickyPi) +- [#4401](https://github.com/rollup/rollup/pull/4401): Improve test stability by getting independent of module id ordering in more places (@lukastaegert) +- [#4403](https://github.com/rollup/rollup/pull/4403): fix: remove unnecessary property descriptor spread (@dnalborczyk) +- [#4404](https://github.com/rollup/rollup/pull/4404): refactor: use map for import descriptions + re-export descriptions (@dnalborczyk) +- [#4405](https://github.com/rollup/rollup/pull/4405): refactor: module exports to map (@dnalborczyk) +- [#4406](https://github.com/rollup/rollup/pull/4406): Fix a typo in 'Direct plugin communication' code example (@younesmln) +- [#4407](https://github.com/rollup/rollup/pull/4407): Document how resolveId is cached (@lukastaegert) +- [#4409](https://github.com/rollup/rollup/pull/4409): Print ids for unfinished moduleParsed and shouldTransformCachedModule hooks (@lukastaegert) + +## 2.67.2 + +_2022-02-10_ + +### Bug Fixes + +- Ensure consistent order between manual chunks to fix hashing issues (#4397) + +### Pull Requests + +- [#4390](https://github.com/rollup/rollup/pull/4390): refactor: add @types/estree explicitly, fix dynamic type imports (@dnalborczyk) +- [#4391](https://github.com/rollup/rollup/pull/4391): chore: remove acorn-walk ambient type definitions (@dnalborczyk) +- [#4397](https://github.com/rollup/rollup/pull/4397): Sort manual chunks generated via a function by name (@lukastaegert) + +## 2.67.1 + +_2022-02-07_ + +### Bug Fixes + +- Make chunk file and variable names more deterministic when emitting chunks (#4386) +- Improve default module resolver performance by using non-blocking IO (#4386) + +### Pull Requests + +- [#4373](https://github.com/rollup/rollup/pull/4373): fix: even more types (@dnalborczyk) +- [#4382](https://github.com/rollup/rollup/pull/4382): Update contribution tut link desc (@lemredd) +- [#4383](https://github.com/rollup/rollup/pull/4383): chore: bump deps (@dnalborczyk) +- [#4384](https://github.com/rollup/rollup/pull/4384): chore: move "wait" to utils + re-use (@dnalborczyk) +- [#4385](https://github.com/rollup/rollup/pull/4385): refactor: convert watch tests to async functions (@dnalborczyk) +- [#4386](https://github.com/rollup/rollup/pull/4386): refactor: use fs.promises in resolve id, Part 4 (@dnalborczyk and @lukastaegert) +- [#4389](https://github.com/rollup/rollup/pull/4389): refactor: use fs.promises in generate license file, rollup config, Part 5 (@dnalborczyk) + +## 2.67.0 + +_2022-02-02_ + +### Features + +- Improve side effect detection when using Array.prototype.groupBy/groupByToMap (#4360) +- Allow changing `moduleSideEffects` at any time during the build (#4379) +- Soft-deprecate `ModuleInfo.hasModuleSideEffects` in favour of `ModuleInfo.moduleSideEffects` (#4379) + +### Bug Fixes + +- Do not include queries and hashes in generated file names when preserving modules (#4374) + +### Pull Requests + +- [#4319](https://github.com/rollup/rollup/pull/4319): refactor: use fs, fs-extra, remove sander (@dnalborczyk) +- [#4360](https://github.com/rollup/rollup/pull/4360): feat: add Array.prototype.groupBy/groupByToMap (@dnalborczyk) +- [#4361](https://github.com/rollup/rollup/pull/4361): fix: more types (@dnalborczyk) +- [#4369](https://github.com/rollup/rollup/pull/4369): fix: remove acorn-walk patch (@dnalborczyk) +- [#4371](https://github.com/rollup/rollup/pull/4371): refactor: use fs.promises in cli/run (@dnalborczyk) +- [#4372](https://github.com/rollup/rollup/pull/4372): refactor: use fs.promises in module loader (@dnalborczyk) +- [#4374](https://github.com/rollup/rollup/pull/4374): Ignore queries and hashes in file names when preserving modules (@lukastaegert) +- [#4375](https://github.com/rollup/rollup/pull/4375): Fix typo in \_config.js (@eltociear) +- [#4376](https://github.com/rollup/rollup/pull/4376): refactor: fs.promises, move mkdir to writeoutputfile, Part 3 (@dnalborczyk) +- [#4379](https://github.com/rollup/rollup/pull/4379): Deprecate hasModuleSideEffects in favor of moduleSideEffects and ensure it is mutable on ModuleInfo (@lukastaegert) + +## 2.66.1 + +_2022-01-25_ + +### Bug Fixes + +- Only warn for conflicting names in namespace reexports if it actually causes problems (#4363) +- Only allow explicit exports or reexports as synthetic namespaces and hide them from namespace reexports (#4364) + +### Pull Requests + +- [#4362](https://github.com/rollup/rollup/pull/4362): refactor: convert exportsByName object to map (@dnalborczyk) +- [#4363](https://github.com/rollup/rollup/pull/4363): Do not warn unnecessarily for namespace conflicts (@lukastaegert) +- [#4364](https://github.com/rollup/rollup/pull/4364): Do not expose synthetic namespace export in entries and namespaces (@lukastaegert) + +## 2.66.0 + +_2022-01-22_ + +### Features + +- Note if a module has a default export in ModuleInfo to allow writing better proxy modules (#4356) +- Add option to wait until all imported ids have been resolved when awaiting `this.load` (#4358) + +### Pull Requests + +- [#4356](https://github.com/rollup/rollup/pull/4356): Add hasDefaultExport to ModuleInfo (@lukastaegert) +- [#4358](https://github.com/rollup/rollup/pull/4358): Add "resolveDependencies" option to "this.load" (@lukastaegert) + +## 2.65.0 + +_2022-01-21_ + +### Features + +- Add complete import resolution objects to ModuleInfo for use in `this.load` (#4354) + +### Bug Fixes + +- Use correct context in plugin hooks with `perf: true` (#4357) + +### Pull Requests + +- [#4351](https://github.com/rollup/rollup/pull/4351): refactor: re-use source mapping url (@dnalborczyk) +- [#4352](https://github.com/rollup/rollup/pull/4352): refactor: replace require-relative with built-in require.resolve (@dnalborczyk) +- [#4353](https://github.com/rollup/rollup/pull/4353): chore: bump deps (@dnalborczyk) +- [#4354](https://github.com/rollup/rollup/pull/4354): Add importedIdResolutions to moduleInfo (@lukastaegert) +- [#4355](https://github.com/rollup/rollup/pull/4355): chore: remove external from config (@dnalborczyk) +- [#4357](https://github.com/rollup/rollup/pull/4357): fix: timed plugin context (@dnalborczyk) + +## 2.64.0 + +_2022-01-14_ + +### Features + +- Allow inspecting cached modules and forcing them to be transformed again via shouldTransformCachedModule (#4320) +- Do not wait for the config file to be parsed in watch mode if it is updated before that (#4344) + +### Bug Fixes + +- Do not mutate objects returned as `meta` from the resolveId hook (#4347) + +### Pull Requests + +- [#4326](https://github.com/rollup/rollup/pull/4326): refactor: type fixes (@dnalborczyk) +- [#4339](https://github.com/rollup/rollup/pull/4339): More watch test stabilization (@lukastaegert) +- [#4340](https://github.com/rollup/rollup/pull/4340): refactor: performance timers for node.js and browser (@dnalborczyk) +- [#4341](https://github.com/rollup/rollup/pull/4341): Implement shouldTransformCachedModule hook (@lukastaegert) +- [#4344](https://github.com/rollup/rollup/pull/4344): Directly restart Rollup when config file change is detected in watch mode (@lukastaegert) +- [#4347](https://github.com/rollup/rollup/pull/4347): Create a shallow copy when returning meta from resolveId (@lukastaegert) + +## 2.63.0 + +_2022-01-04_ + +### Features + +- Report a helpful error if rollup exits due to an empty event loop when using `this.load` (#4320) +- Allow directly mutating ModuleInfo.meta for modules and never replace this object (#4328) +- Detect additional side effect free array prototype methods (#4332) + +### Bug Fixes + +- Do not watch if CLI watch options are specified but `--watch` is missing (#4335) + +### Pull Requests + +- [#4320](https://github.com/rollup/rollup/pull/4320): Detect unfulfilled async hook actions and report error on exit (@kzc) +- [#4328](https://github.com/rollup/rollup/pull/4328): Make initial ModuleInfo.meta mutable and maintain object identity (@lukastaegert) +- [#4318](https://github.com/rollup/rollup/pull/4318): Stabilize watch tests (@lukastaegert) +- [#4331](https://github.com/rollup/rollup/pull/4331): Improve JS docs example (@lukastaegert) +- [#4332](https://github.com/rollup/rollup/pull/4332): add support for Array.prototype.findLast,findLastIndex (@dnalborczyk) +- [#4333](https://github.com/rollup/rollup/pull/4333): convert utils.transform to async function (@dnalborczyk) +- [#4335](https://github.com/rollup/rollup/pull/4335): Do not watch unless --watch is specified explicitly (@lukastaegert) +- [#4338](https://github.com/rollup/rollup/pull/4338): Add build delay for plugin event test (@lukastaegert) + +## 2.62.0 + +_2021-12-24_ + +### Features + +- Mark additional string prototype methods as side-effect-free and correct typings of existing ones (#4299) +- Mark additional array prototype methods as side-effect-free and correct typings of existing ones (#4309) +- Expose if a module is included after tree-shaking in its ModuleInfo (#4305) + +### Bug Fixes + +- Fix how fsevents is included to improve watch mode on MacOS (#4312) + +### Pull Requests + +- [#4299](https://github.com/rollup/rollup/pull/4299): Add additional string prototype methods (@dnalborczyk) +- [#4300](https://github.com/rollup/rollup/pull/4300): Bump deps, fix expected test result for core-js (@dnalborczyk) +- [#4302](https://github.com/rollup/rollup/pull/4302): Replace type assertion with type guard (@dnalborczyk) +- [#4304](https://github.com/rollup/rollup/pull/4304): Re-use reserved names set (@dnalborczyk) +- [#4305](https://github.com/rollup/rollup/pull/4305): Expose isIncluded in module info (@william57m) +- [#4306](https://github.com/rollup/rollup/pull/4306): Fix git line breaks on windows (@dnalborczyk) +- [#4307](https://github.com/rollup/rollup/pull/4307): Add macos to pipeline (@dnalborczyk) +- [#4309](https://github.com/rollup/rollup/pull/4309): Add additional array prototype methods (@dnalborczyk) +- [#4311](https://github.com/rollup/rollup/pull/4311): Add Deno instructions to docs (@jespertheend) +- [#4312](https://github.com/rollup/rollup/pull/4312): fsevents integration (@dnalborczyk) +- [#4313](https://github.com/rollup/rollup/pull/4313): Remove non-existing static functions from known globals (@dnalborczyk) + +## 2.61.1 + +_2021-12-11_ + +### Bug Fixes + +- Only resolve this.load once the code of the module is available (#4296) + +### Pull Requests + +- [#4296](https://github.com/rollup/rollup/pull/4296): Make sure this.load waits for modules that are already loading (@lukastaegert) +- [#4298](https://github.com/rollup/rollup/pull/4298): use set for reserved words (@dnalborczyk) + +## 2.61.0 + +_2021-12-09_ + +### Features + +- Support ergonomic brand checks for private fields (#4293) + +### Bug Fixes + +- Improve handling of directory creation on systems with restrictive open files limit (#4288) + +### Pull Requests + +- [#4288](https://github.com/rollup/rollup/pull/4288): modifymkdirpath (@mgrabowski84) +- [#4293](https://github.com/rollup/rollup/pull/4293): bump deps (@dnalborczyk) + +## 2.60.2 + +_2021-11-30_ + +### Bug Fixes + +- Produce correct output when dynamic import paths contain quotes (#4286) + +### Pull Requests + +- [#4286](https://github.com/rollup/rollup/pull/4286): Escape dynamic import paths (@danielroe) + +## 2.60.1 + +_2021-11-22_ + +### Bug Fixes + +- Make sure virtual files have proper file extensions when preserving modules (#4270) + +### Pull Requests + +- [#4270](https://github.com/rollup/rollup/pull/4270): Use entryFileNames when generating filenames for virtual modules (@BPScott) + +## 2.60.0 + +_2021-11-11_ + +### Features + +- Add `this.load` context function to load, transform and parse modules without adding them to the graph (#4234) +- Sanitize non-url-safe characters in generated chunk names by default (#4262) +- Support ESM plugins via command line (#4265) + +### Pull Requests + +- [#4234](https://github.com/rollup/rollup/pull/4234): Plugin context function for pre-loading modules (@lukastaegert) +- [#4262](https://github.com/rollup/rollup/pull/4262): exclude invalid URL chars (@danielroe) +- [#4265](https://github.com/rollup/rollup/pull/4265): support loading ESM plugins from the CLI via --plugin (@kzc) + +## 2.59.0 + +_2021-11-01_ + +### Features + +- Support static class initialization blocks (#4249) + +### Bug Fixes + +- Fix an issue with the CommonJS plugin when module.exports has inherited properties (#4256) + +### Pull Requests + +- [#4236](https://github.com/rollup/rollup/pull/4236): typescript bug class field initialization order (@dnalborczyk) +- [#4249](https://github.com/rollup/rollup/pull/4249): Support for class static initialization block (@dnalborczyk and @lukastaegert) +- [#4256](https://github.com/rollup/rollup/pull/4256): Skip inherited properties in synthetic namespaces (@lukastaegert) + +## 2.58.3 + +_2021-10-25_ + +### Bug Fixes + +- Republish 2.58.1 with npm 6 as files were missing + +## 2.58.2 + +_2021-10-25_ + +### Bug Fixes + +- Republish 2.58.1 as files were missing + +## 2.58.1 + +_2021-10-25_ + +### Bug Fixes + +- Fix an issue with the CommonJS plugin when module.exports is falsy (#4247) + +### Pull Requests + +- [#4247](https://github.com/rollup/rollup/pull/4247): Handle falsy synthetic namespaces (@lukastaegert) + +## 2.58.0 + +_2021-10-01_ + +### Features + +- Add a flag to more reliably identify entry points in the `resolveId` hook (#4230) + +### Pull Requests + +- [#4230](https://github.com/rollup/rollup/pull/4230): Add isEntry flag to resolveId and this.resolve (@lukastaegert) +- [#4233](https://github.com/rollup/rollup/pull/4233): Remove unused rollup-plugin-typescript ambient module types (@dnalborczyk) +- [#4235](https://github.com/rollup/rollup/pull/4235): Update dependencies (@lukastaegert) + +## 2.57.0 + +_2021-09-22_ + +### Features + +- Add `generatedCode` option to allow Rollup to use es2015 features for smaller output and more efficient helpers (#4215) +- Improve AMD and SystemJS parsing performance by wrapping relevant functions in parentheses (#4215) +- Using `preferConst` will now show a warning with `strictDeprecations: true` (#4215) + +### Bug Fixes + +- Improve ES3 syntax compatibility by more consequently quoting reserved words as props in generated code (#4215) +- Do not use `Object.assign` in generated code to ensure ES5 compatibility without the need for polyfills (#4215) +- Support live-bindings in dynamic namespace objects that contain reexported external or synthetic namespaces (#4215) +- Use correct "this" binding in dynamic import expressions for CommonJS and AMD (#4215) +- Properly handle `shimMissingExports` for exports that are only used internally (#4215) +- Prevent unhandled rejection for failed module parsing (#4228) + +### Pull Requests + +- [#4212](https://github.com/rollup/rollup/pull/4212): chore: remove unused ambient types (@dnalborczyk) +- [#4215](https://github.com/rollup/rollup/pull/4215): Use ES2015 features in generated code snippets (@lukastaegert) +- [#4219](https://github.com/rollup/rollup/pull/4219): chore: bump rollup typescript, remove unused micromatch (@dnalborczyk) +- [#4220](https://github.com/rollup/rollup/pull/4220): chore: use forceConsistentCasingInFileNames in ts-config (@dnalborczyk) +- [#4224](https://github.com/rollup/rollup/pull/4224): prepare for useDefineForClassFields (@dnalborczyk) +- [#4228](https://github.com/rollup/rollup/pull/4228): fix: prevent UnhandledPromiseRejectionWarning when module resolution/parsing fails (@kherock) + +## 2.56.3 + +_2021-08-23_ + +### Bug Fixes + +- Make sure moduleInfo contains complete information about imported ids in the moduleParsed hook (#4208) + +### Pull Requests + +- [#4208](https://github.com/rollup/rollup/pull/4208): `ModuleInfo.importedIds` will return null if `resolvedIds[source]` is undefined (@FoxDaxian and @lukastaegert) + +## 2.56.2 + +_2021-08-10_ + +### Bug Fixes + +- Check if after simplification, an object pattern would become an expression statement or arrow function return value (#4204) + +### Pull Requests + +- [#4204](https://github.com/rollup/rollup/pull/4204): Do not create invalid code when simplifying object pattern assignments (@lukastaegert) + +## 2.56.1 + +_2021-08-08_ + +### Bug Fixes + +- Fix rendering of SystemJS export declarations initialized with a simplifiable expression (#4202) + +### Pull Requests + +- [#4202](https://github.com/rollup/rollup/pull/4202): Fix incorrect rendering of export declarations in SystemJS (@lukastaegert) + +## 2.56.0 + +_2021-08-05_ + +### Features + +- Create more efficient code for SystemJS exports (#4199) +- Extend `maxParallelFileReads` option to also throttle plugin load hooks (#4200) + +### Bug Fixes + +- Return correct value for postfix update expressions of exported variables (#4194) + +### Pull Requests + +- [#4199](https://github.com/rollup/rollup/pull/4199): Refine SystemJS export rendering (@lukastaegert) +- [#4200](https://github.com/rollup/rollup/pull/4200): Restrict parallel execution of load hook (@schummar) + +## 2.55.1 + +_2021-07-29_ + +### Bug Fixes + +- Improve CLI warning message for unused external imports (#4194) + +### Pull Requests + +- [#4194](https://github.com/rollup/rollup/pull/4194): Align batch warning for UNUSED_EXTERNAL_IMPORT to individual warning (@benmccann) + +## 2.55.0 + +_2021-07-28_ + +### Features + +- Support default export live-bindings when generating ESM output (#4182) + +### Bug Fixes + +- Always write `["default"]` as computed property when used as named export (#4182) +- Do not mask default export TDZ errors (#4182) + +### Pull Requests + +- [#4182](https://github.com/rollup/rollup/pull/4182): Use mutable bindings for default exports (@lukastaegert) + +## 2.54.0 + +_2021-07-25_ + +### Features + +- Extend UMD import.meta.url polyfill to support web workers (#4186) + +### Bug Fixes + +- Resolve an issue where certain uses of classes could lead to an infinite recursion (#4189) + +### Pull Requests + +- [#4186](https://github.com/rollup/rollup/pull/4186): Fix UMD import.meta.url inside web workers (@ceifa) +- [#4188](https://github.com/rollup/rollup/pull/4188): Fix typo in renderHelpers.ts (@eltociear) +- [#4189](https://github.com/rollup/rollup/pull/4189): Move long path recursion prevention to MemberExpression (@lukastaegert) +- [#4190](https://github.com/rollup/rollup/pull/4190): Stop recommending node-builtins (@curran) + +## 2.53.3 + +_2021-07-21_ + +### Bug Fixes + +- Solve an issue that could lead to severe memory issues and crashes when there are a lot of hoisted variables (#4183) + +### Pull Requests + +- [#4183](https://github.com/rollup/rollup/pull/4183): Avoid memory issues with hoisted variables (@lukastaegert) + +## 2.53.2 + +_2021-07-15_ + +### Bug Fixes + +- Identify additional TDZ situations in functions that are run more than once (#4177) +- Fix a scoping issue when a variable inside a catch scope matches the scope parameter's name (#4178) + +### Pull Requests + +- [#4177](https://github.com/rollup/rollup/pull/4177): Fix additional let/var init bugs (@kzc) +- [#4178](https://github.com/rollup/rollup/pull/4178): Correctly create outside variable when shadowed by catch parameter (@lukastaegert) + +## 2.53.1 + +_2021-07-11_ + +### Bug Fixes + +- Do not omit namespace reexports when `treeshake` is `false` (#4175) + +### Pull Requests + +- [#4175](https://github.com/rollup/rollup/pull/4175): Generate namespace objects when not tree-shaking (@lukastaegert) + +## 2.53.0 + +_2021-07-09_ + +### Features + +- Add `maxParallelFileReads` option to limit read operations with a default of 20 (#4170) + +### Pull Requests + +- [#4170](https://github.com/rollup/rollup/pull/4170): Limit parallel file reads to prevent "EMFILE: too many open files" error (@schummar) + +## 2.52.8 + +_2021-07-07_ + +### Bug Fixes + +- Automatically handle many use `var` before declaration and TDZ access scenarios correctly without the need for `treeshake.correctVarValueBeforeDeclaration` (#4148) + +### Pull Requests + +- [#4148](https://github.com/rollup/rollup/pull/4148): Fix var/const/let variable use before declaration (@kzc and @lukastaegert) + +## 2.52.7 + +_2021-07-02_ + +### Bug Fixes + +- Fix an issue where reassignments where not tracked through async function returns (#4163) + +### Pull Requests + +- [#4163](https://github.com/rollup/rollup/pull/4163): Deoptimize return values of async functions (@lukastaegert) + +## 2.52.6 + +_2021-07-01_ + +### Bug Fixes + +- Fix an issue where reassignments where not tracked through an await expression (#4162) + +### Pull Requests + +- [#4162](https://github.com/rollup/rollup/pull/4162): doptimize awaited expressions (@lukastaegert) + +## 2.52.5 + +_2021-07-01_ + +### Bug Fixes + +- Properly display parser errors not tied to a code location (#4160) + +### Pull Requests + +- [#4160](https://github.com/rollup/rollup/pull/4160): fix: max stack call error is caught on locate (@semoal) + +## 2.52.4 + +_2021-06-30_ + +### Bug Fixes + +- Fix an error when external namespaces are reexported across several files (#4159) + +### Pull Requests + +- [#4159](https://github.com/rollup/rollup/pull/4159): Properly handle double reexports from external namespaces (@lukastaegert) + +## 2.52.3 + +_2021-06-25_ + +### Bug Fixes + +- Fix an issue where code was wrongly removed when using vars in nested scopes (#4149) + +### Pull Requests + +- [#4149](https://github.com/rollup/rollup/pull/4149): Make sure the initializer of hoisted variables is deoptimized (@lukastaegert) + +## 2.52.2 + +_2021-06-21_ + +### Bug Fixes + +- Support falsy plugins in types (#4144) +- Do not require return value in renderChunkHook type (#4144) + +### Pull Requests + +- [#4144](https://github.com/rollup/rollup/pull/4144): Use TypeScript config and improve some types (@lukastaegert) + +## 2.52.1 + +_2021-06-17_ + +### Bug Fixes + +- Fix a memory leak in watch mode (#4142) + +### Pull Requests + +- [#4142](https://github.com/rollup/rollup/pull/4142): Make array and object prototype singletons immutable for now (@lukastaegert) + +## 2.52.0 + +_2021-06-16_ + +### Features + +- Add `--configPlugin` CLI option to apply plugins to the config file for e.g. TypeScript configs (#3835) +- Add "safest" and "smallest" presets to tree-shaking options for easier configuration (#4131) +- Add `treeshake.correctVarValueBeforeDeclaration` option to deoptimize `var` declarations (#4139) + +### Pull Requests + +- [#3835](https://github.com/rollup/rollup/pull/3835): Add typescript config support (@TheRealSyler) +- [#4131](https://github.com/rollup/rollup/pull/4131): Add presets to the tree-shaking options (@lukastaegert) +- [#4139](https://github.com/rollup/rollup/pull/4139): Add option to deoptimize var declarations for tree-shaking (@lukastaegert) +- [#4141](https://github.com/rollup/rollup/pull/4141): Update dependencies (@lukastaegert) + +## 2.51.2 + +_2021-06-11_ + +### Bug Fixes + +- Include modules imported from no-treeshake modules even if they would be empty (#4138) + +### Pull Requests + +- [#4138](https://github.com/rollup/rollup/pull/4138): Include all dependencies from modules with no-treeshake (@lukastaegert) + +## 2.51.1 + +_2021-06-08_ + +### Bug Fixes + +- Fix error when using `defineConfig` (#4134) + +### Pull Requests + +- [#4134](https://github.com/rollup/rollup/pull/4134): export `rollup.defineConfig` at runtime (@mshrtsr) + +## 2.51.0 + +_2021-06-06_ + +### Features + +- Add a helper for IntelliSense support in config files (#4127) + +### Bug Fixes + +- Improve performance when generating source maps (#4122) + +### Pull Requests + +- [#4122](https://github.com/rollup/rollup/pull/4122): User Map to optimize performance (@izevo) +- [#4127](https://github.com/rollup/rollup/pull/4127): Export defineConfig defines the auxiliary function of the configuration (@rxliuli) + +## 2.50.6 + +_2021-06-03_ + +### Bug Fixes + +- Do not consider the object spread operator as side effect when `propertyReadSideEffects` are false (#4119) +- Detect side effects when returning thenables from async arrow functions (#4120) + +### Pull Requests + +- [#4119](https://github.com/rollup/rollup/pull/4119): Respect propertyReadSideEffects in spread elements (@lukastaegert) +- [#4120](https://github.com/rollup/rollup/pull/4120): Detect async arrow thenable side effects (@lukastaegert) + +## 2.50.5 + +_2021-05-30_ + +### Bug Fixes + +- Detect side effects when accessing thenables (#4115) + +### Pull Requests + +- [#4114](https://github.com/rollup/rollup/pull/4114): use `colorette` instead of `turbocolor` (@ryuever) +- [#4115](https://github.com/rollup/rollup/pull/4115): Tracks side effects of thenables (@lukastaegert) + +## 2.50.4 + +_2021-05-29_ + +### Bug Fixes + +- Fix a situation where tree-shaking would stop including nodes prematurely (#4111) +- Track mutations and accessor side effects when using `__proto__` in an object literal (#4112) +- Check for getter effects when spreading an object (#4113) + +### Pull Requests + +- [#4111](https://github.com/rollup/rollup/pull/4111): Always request a new tree-shaking pass when deoptimizations of a node are first included (@lukastaegert) +- [#4112](https://github.com/rollup/rollup/pull/4112): Actually set the prototype when using a **proto** property (@lukastaegert) +- [#4113](https://github.com/rollup/rollup/pull/4113): Track access side effects when using object spread operator (@lukastaegert) + +## 2.50.3 + +_2021-05-28_ + +### Bug Fixes + +- Wrap parentheses around leading elements in simplified sequence expressions if this would otherwise lead to invalid code (#4110) +- Do not associate block soped variables in catch clauses with the clause parameter (#4108) +- Do not associate hoisted variables in catch clauses with outside variables if they match the parameter (#4108) +- Use correct "this" context for tagged template literal member expressions in simplified sequences (#4110) + +### Pull Requests + +- [#4108](https://github.com/rollup/rollup/pull/4108): Correctly handle catch declarations (@lukastaegert) +- [#4110](https://github.com/rollup/rollup/pull/4110): Invalid sequence expression simplification (@lukastaegert) + +## 2.50.2 + +_2021-05-27_ + +### Bug Fixes + +- Avoid unnecessary side effects when using methods like `.filter` and `.map` (#4103) +- Avoid crash when a module with moduleSideEffects no-treeshake imports a tree-shaken module (#4104) + +### Pull Requests + +- [#4103](https://github.com/rollup/rollup/pull/4103): Do not track side-effect-free array methods as side effects (@lukastaegert) +- [#4104](https://github.com/rollup/rollup/pull/4104): Fix crash when using inlineDynamicImports with no-treeshake (@lukastaegert) + +## 2.50.1 + +_2021-05-26_ + +### Bug Fixes + +- Do not associate pure annotations in simplified expressions with wrong elements (#4095) +- Prevent invalid code when simplified conditionals start with an IIFE function expression (#4099) + +### Pull Requests + +- [#4095](https://github.com/rollup/rollup/pull/4095): Correctly associate pure annotations and remove invalid ones (@lukastaegert) +- [#4099](https://github.com/rollup/rollup/pull/4099): Wrap leading function expression iifes in conditionals (@lukastaegert) + +## 2.50.0 + +_2021-05-25_ + +### Features + +- Only include last elements of comma expressions if they are used or have side effects (#4087) + +### Bug Fixes + +- Prevent a crash that could occur when calling object methods (#4091) + +### Pull Requests + +- [#4085](https://github.com/rollup/rollup/pull/4085): Switch to ESLint (@lukastaegert) +- [#4087](https://github.com/rollup/rollup/pull/4087): Drop unused last sequence element (@lukastaegert) +- [#4091](https://github.com/rollup/rollup/pull/4091): Prevent crash for recursive "this" deoptimization (@lukastaegert) + +## 2.49.0 + +_2021-05-23_ + +### Features + +- Detect side-effect-free static class methods and properties (#4018) +- Detect side-effect-free array elements (#4018) +- Do not apply deoptimizations from dead code (#4018) + +### Bug Fixes + +- Handle side effect detection for getters and setters added in untracked code (#4018) +- Track "this" mutations for methods, getters and setters (#4018) + +### Pull Requests + +- [#4018](https://github.com/rollup/rollup/pull/4018): Class method effects (@marijnh and @lukastaegert) + +## 2.48.0 + +_2021-05-15_ + +### Features + +- Add replacement to conditionally insert asset extensions in `entryFileNames` when preserving modules (#4077) + +### Bug Fixes + +- Fix crash when dynamically assigning to namespace members (#4070) +- Do not associate pure annotations in front of a semi-colon or comma with succeeding code (#4068) + +### Pull Requests + +- [#4068](https://github.com/rollup/rollup/pull/4068): ignore invalid trailing pure annotations (@kzc) +- [#4070](https://github.com/rollup/rollup/pull/4070): undefined `deoptimizePath` when the first element is empty string (@si3nloong) +- [#4071](https://github.com/rollup/rollup/pull/4071): add node.js v16 support (@dnalborczyk) +- [#4077](https://github.com/rollup/rollup/pull/4077): Add assetExtname replacement in entryFileNames (@BPScott) +- [#4080](https://github.com/rollup/rollup/pull/4080): Added Rollup logo in README.md (@priyanshurav) +- [#4081](https://github.com/rollup/rollup/pull/4081): fix comment regarding invalid annotation handling (@kzc) + +## 2.47.0 + +_2021-05-04_ + +### Features + +- Warn about ambiguous imports from combined external namespace reexports (#4064) +- In case of combined namespace reexports, always prefer local exports over external namespaces (#4064) +- Treat conflicting names in local namespace reexports as undefined (#4064) + +### Pull Requests + +- [#4064](https://github.com/rollup/rollup/pull/4064): Prefer locally defined exports and reexports over external namespaces (@lukastaegert) + +## 2.46.0 + +_2021-04-29_ + +### Features + +- Add option to disable file name sanitation (#4058) +- Add information about importers to unused external import warning (#4054) + +### Pull Requests + +- [#4042](https://github.com/rollup/rollup/pull/4042): Use Github actions only (@lukastaegert) +- [#4045](https://github.com/rollup/rollup/pull/4045): Fix REPL artefact branch reference (@lukastaegert) +- [#4046](https://github.com/rollup/rollup/pull/4046): Use codecov action for coverage (@lukastaegert) +- [#4054](https://github.com/rollup/rollup/pull/4054): Add to `UNUSED_EXTERNAL_IMPORT` warning information about the origin of the problem (@cawa-93) +- [#4058](https://github.com/rollup/rollup/pull/4058): Add sanitizeFileName option (@guybedford) + +## 2.45.2 + +_2021-04-13_ + +### Bug Fixes + +- Do not user a dynamic entry file name for naming a manual chunk (#4040) + +### Pull Requests + +- [#4040](https://github.com/rollup/rollup/pull/4040): Prioritize manual chunk name over dynamic entry id (@lukastaegert) + +## 2.45.1 + +_2021-04-10_ + +### Bug Fixes + +- Handle falsy return values from async plugin options hooks (#4039) + +### Pull Requests + +- [#4039](https://github.com/rollup/rollup/pull/4039): Do not fail when returning null or undefined from an async options hook (@lukastaegert) + +## 2.45.0 + +_2021-04-09_ + +### Features + +- Support private class instance methods and accessors (#4034) + +### Pull Requests + +- [#4034](https://github.com/rollup/rollup/pull/4034): feat: add support for private class methods (@dnalborczyk) + +## 2.44.0 + +_2021-03-29_ + +### Features + +- Add a new option `makeAbsoluteExternalsRelative` to opt out of renormalizing absolute external ids to relative ids (#4021) +- Extend the `resolveId` plugin hook to allow forcing or preventing renormalization of absolute external ids (#4021) +- Make the rendered code of individual modules available in the generated bundle (#4028) + +### Bug Fixes + +- Handle objects with `__proto__` properties correctly (#4019) + +### Pull Requests + +- [#4019](https://github.com/rollup/rollup/pull/4019): Deoptimize ObjectExpression when a `__proto__` property is present (@marijnh) +- [#4021](https://github.com/rollup/rollup/pull/4021): Improve absolute path handling (@lukastaegert) +- [#4026](https://github.com/rollup/rollup/pull/4026): chore: fix vscode launch config (change tdd to bdd) (@jameslahm) +- [#4027](https://github.com/rollup/rollup/pull/4027): Post comment for PRs from forks (@lukastaegert) +- [#4028](https://github.com/rollup/rollup/pull/4028): Expose rendered module code to generateBundle hook (@btd) + +## 2.43.1 + +_2021-03-28_ + +### Bug Fixes + +- Prevent infinite recursions in certain scenarios when calling object properties (#4025) + +### Pull Requests + +- [#4025](https://github.com/rollup/rollup/pull/4025): Handle recursive this mutation detection (@lukastaegert) + +## 2.43.0 + +_2021-03-27_ + +### Features + +- Track side effects of function properties in objects for better tree-shaking (#4011) + +### Pull Requests + +- [#4011](https://github.com/rollup/rollup/pull/4011): Disable pessimistic object deoptimization for calls when the called function doesn't ref this (@marijnh) +- [#4012](https://github.com/rollup/rollup/pull/4012): fix `sourcemap` reference in docs (@tjenkinson) +- [#4015](https://github.com/rollup/rollup/pull/4015): Use SIGTERM instead of SIGINT to kill test child processes in tests (@marijnh) + +## 2.42.4 + +_2021-03-24_ + +### Bug Fixes + +- Do not discard plugin return values when using perf option (#4010) + +### Pull Requests + +- [#4010](https://github.com/rollup/rollup/pull/4010): Return hook result inside promise with async timer end (@SuperOleg39) + +## 2.42.3 + +_2021-03-22_ + +### Bug Fixes + +- Do not ignore `#__PURE__` comments in front of optional chaining expressions (#4007) + +### Pull Requests + +- [#4007](https://github.com/rollup/rollup/pull/4007): Tree-shake pure call expressions with optional chaining (@lukastaegert) + +## 2.42.2 + +_2021-03-22_ + +### Bug Fixes + +- Use correct import.meta.url in relative imports from transpiled config files (#4005) + +### Pull Requests + +- [#4005](https://github.com/rollup/rollup/pull/4005): Use correct import.meta.url in config files (@lukastaegert) + +## 2.42.1 + +_2021-03-20_ + +### Bug Fixes + +- Do not produce unhandled Promise rejections when plugins throw while using the `perf` option (#4004) + +### Pull Requests + +- [#4004](https://github.com/rollup/rollup/pull/4004): Fixed unhandled promise rejections (@gluck) + +## 2.42.0 + +_2021-03-19_ + +### Features + +- Prevent infinite loops when several plugins are using `this.resolve` in their resolveId hook (#4000) + +### Pull Requests + +- [#4000](https://github.com/rollup/rollup/pull/4000): Break infinite loops in this.resolve (@lukastaegert) + +## 2.41.5 + +_2021-03-18_ + +### Bug Fixes + +- Make sure unused property accesses of external namespaces can be tree-shaken (#4001) + +### Pull Requests + +- [#4001](https://github.com/rollup/rollup/pull/4001): Do not count accessing members of an external namespace as side-effects (@lukastaegert) + +## 2.41.4 + +_2021-03-16_ + +### Bug Fixes + +- Do not replace external namespace imports with individual named imports to avoid changing behaviour with regard to missing exports (#3999) + +### Pull Requests + +- [#3999](https://github.com/rollup/rollup/pull/3999): Allow to safely probe external namespaces (@lukastaegert) + +## 2.41.3 + +_2021-03-16_ + +### Bug Fixes + +- Always retain arguments passed to empty object pattern parameters (#3998) + +### Pull Requests + +- [#3998](https://github.com/rollup/rollup/pull/3998): Do not create invalid code if a function argument is an empty object pattern (@lukastaegert) + +## 2.41.3 + +_2021-03-16_ + +### Bug Fixes + +- Always retain arguments passed to empty object pattern parameters (#3998) + +### Pull Requests + +- [#3998](https://github.com/rollup/rollup/pull/3998): Do not create invalid code if a function argument is an empty object pattern (@lukastaegert) + +## 2.41.2 + +_2021-03-12_ + +### Bug Fixes + +- Also remove sourcemaps comments if plugins return a pre-made ast (#3987) + +### Pull Requests + +- [#3987](https://github.com/rollup/rollup/pull/3987): Change removal of sourcemap comment (@yannayl) + +## 2.41.1 + +_2021-03-11_ + +### Pull Requests + +- [#3990](https://github.com/rollup/rollup/pull/3990): Add browser sourcemap and remove log (@lukastaegert) + +## 2.41.0 + +_2021-03-09_ + +### Features + +- Add option to `treeshake.propertyReadSideEffects` to keep all property accesses (#3985) + +### Bug Fixes + +- Also respect pure comment annotations when a plugin provides an AST in the transform hook provided they use this.parse (#3981) + +### Pull Requests + +- [#3981](https://github.com/rollup/rollup/pull/3981): Move pure comment annotation to Graph.contextParse (@yannayl) +- [#3985](https://github.com/rollup/rollup/pull/3985): implement --treeshake.propertyReadSideEffects=always to handle getters with side effects (@kzc) + +## 2.40.0 + +_2021-02-26_ + +### Features + +- Make sure that entry point variable names take precedence over variable names in dependencies when deconflicting (#3977) + +### Bug Fixes + +- Replace `:` in generated file names to prevent invalid files on Windows (#3972) + +### Pull Requests + +- [#3972](https://github.com/rollup/rollup/pull/3972): Don't allow `:` in file names (@lukastaegert) +- [#3976](https://github.com/rollup/rollup/pull/3976): Add soft breaks to guide to improve mobile experience (@lukastaegert) +- [#3977](https://github.com/rollup/rollup/pull/3977): Reverse module deconflicting order (@lukastaegert) + +## 2.39.1 + +_2021-02-23_ + +### Bug Fixes + +- Make sure local variables named Symbol, Object or Promise do not conflict with code generated by Rollup (#3971) + +### Pull Requests + +- [#3964](https://github.com/rollup/rollup/pull/3964): Remove extra word (@jamonholmgren) +- [#3971](https://github.com/rollup/rollup/pull/3971): Avoid conflicts with local variables named Symbol, Object, Promise (@lukastaegert) + +## 2.39.0 + +_2021-02-12_ + +### Features + +- Add "validate" option to verify generated chunks are valid JavaScript (#3952) + +### Bug Fixes + +- Always add exports properties for uninitialized named exports (#3957) +- Allow using an external namespace reexport together with named exports (#3959) +- Avoid invalid generated code in certain scenarios with SystemJS exports (#3960) + +### Pull Requests + +- [#3952](https://github.com/rollup/rollup/pull/3952): implement `validate` output option and `--validate` CLI option (@kzc) +- [#3956](https://github.com/rollup/rollup/pull/3956): Update dependencies, fix fsevents issue (@lukastaegert) +- [#3957](https://github.com/rollup/rollup/pull/3957): Make sure uninitialised exports turn up via .hasOwnProperty for non-ES formats (@lukastaegert) +- [#3959](https://github.com/rollup/rollup/pull/3959): Allow overriding individual exports of reexported external namespaces (@lukastaegert) +- [#3960](https://github.com/rollup/rollup/pull/3960): Make sure system exports are valid JavaScript (@lukastaegert) + +## 2.38.5 + +_2021-02-05_ + +### Bug Fixes + +- Prevent invalid code when simplifying assignments and delcarations (#3951) +- Prevent behaviour-changing line-breaks when simplifying assignments in return statements (#3951) +- Slightly improve white-space rendering when simplifying certain expressions (#3951) + +### Pull Requests + +- [#3951](https://github.com/rollup/rollup/pull/3951): Wrap simplified assignments if necessary (@lukastaegert) + +## 2.38.4 + +_2021-02-02_ + +### Bug Fixes + +- Do not change logic when tree-shaking declarations in if statements or loops (#3947) + +### Pull Requests + +- [#3947](https://github.com/rollup/rollup/pull/3947): Do not tear apart declarations in loop or if bodies (@lukastaegert) + +## 2.38.3 + +_2021-02-01_ + +### Bug Fixes + +- Prevent an unexpected live-binding when default exporting a synthetic named export (#3946) + +### Pull Requests + +- [#3945](https://github.com/rollup/rollup/pull/3945): Upgrade chokidar and fsevents for Apple M1 compatibility (@threepointone) +- [#3946](https://github.com/rollup/rollup/pull/3946): Make sure default exports snapshot synthetic named exports (@lukastaegert) + +## 2.38.2 + +_2021-01-31_ + +### Bug Fixes + +- Do not generate invalid code for partially tree-shaken declarations in for loops (#3943) +- Always include function bodies of functions in side-effect-free modules (#3944) + +### Pull Requests + +- [#3943](https://github.com/rollup/rollup/pull/3943): Do not partially tree-shake unused declarations in for loops (@lukastaegert) +- [#3944](https://github.com/rollup/rollup/pull/3944): Correctly include functions with side effects from side-effect-free modules (@lukastaegert) + +## 2.38.1 + +_2021-01-28_ + +### Bug Fixes + +- Fix internal error when resolving a missing entry point in the browser build (#3935) + +### Pull Requests + +- [#3935](https://github.com/rollup/rollup/pull/3935): fix: remove isolated resolve() for compat with browser distribution (@cmorten and @lukastaegert) +- [#3936](https://github.com/rollup/rollup/pull/3936): Ensure test after() callback is always executed (@Benjamin-Dobell) +- [#3937](https://github.com/rollup/rollup/pull/3937): Modernize references to other software (@ludofischer) + +## 2.38.0 + +_2021-01-22_ + +### Features + +- Entirely remove declared variables that only have an initializer side effect (#3933) + +### Pull Requests + +- [#3933](https://github.com/rollup/rollup/pull/3933): Tree-shake unused declarations while keeping initializer side-effects (@lukastaegert) + +## 2.37.1 + +_2021-01-20_ + +### Pull Requests + +- [#3929](https://github.com/rollup/rollup/pull/3929): Deduplicate acorn import (@lukastaegert) + +## 2.37.0 + +_2021-01-19_ + +### Features + +- Always check modules for side effects that only indirectly reexport a used variable (#3840) +- Warn if a circular dependency would cause wrong execution order when preserving modules (#3840) + +### Bug Fixes + +- Allow consuming synthetic exports via modules that reexport a namespace (#3894) +- Do not crash for circular default reexports (#3840) +- Do not crash for circular synthetic namespaces (#3840) +- Improve circular dependency execution order in certain scenarios (#3840) + +### Pull Requests + +- [#3840](https://github.com/rollup/rollup/pull/3840): Improve circular dependency execution order (@lukastaegert) +- [#3894](https://github.com/rollup/rollup/pull/3894): Always respect synthetic namespaces in namespace reexport (@lukastaegert) + +## 2.36.2 + +_2021-01-16_ + +### Bug Fixes + +- Fix an issue where invalid code was generated for unused assignments with side effects (#3926) + +### Pull Requests + +- [#3926](https://github.com/rollup/rollup/pull/3926): Correctly simplify assignments with parentheses (@lukastaegert) + +## 2.36.1 + +_2021-01-06_ + +### Bug Fixes + +- Solve issues that result in invalid code when partially removing assignments (#3921) + +### Pull Requests + +- [#3921](https://github.com/rollup/rollup/pull/3921): Prevent invalid code when removing assignment target of side-effectful object expression (@lukastaegert) + +## 2.36.0 + +_2021-01-05_ + +### Features + +- Support partial tree-shaking of chained assignments and unused assignment targets (#3919) + +### Pull Requests + +- [#3919](https://github.com/rollup/rollup/pull/3919): Treeshake chained assignment expressions (@lukastaegert) + +## 2.35.1 + +_2020-12-14_ + +### Bug Fixes + +- Allow closing the bundle when watching in case of generate errors by adding the bundle to the error event (#3909) +- Automatically close all bundles on generate errors when watching and using the CLI (#3909) +- Try to create remaining bundles when watching and one of them throws (#3909) + +### Pull Requests + +- [#3909](https://github.com/rollup/rollup/pull/3909): Forward bundle through watch error events (@lukastaegert) + +## 2.35.0 + +_2020-12-14_ + +### Features + +- Add `closeBundle` hook that is triggered by `bundle.close()` in the JS API (#3883) + +### Pull Requests + +- [#3883](https://github.com/rollup/rollup/pull/3883): Revert pattern to folder export (@intrnl) + +## 2.34.2 + +_2020-12-06_ + +### Bug Fixes + +- Revert pattern export change (#3898) + +### Pull Requests + +- [#3898](https://github.com/rollup/rollup/pull/3898): Revert pattern to folder export (@lukastaegert) + +## 2.34.1 + +_2020-12-03_ + +### Bug Fixes + +- Avoid Node deprecation warning by using a pattern export for nested Rollup files (#3896) + +### Pull Requests + +- [#3887](https://github.com/rollup/rollup/pull/3887): Run memory leak test on all systems (@lukastaegert) +- [#3892](https://github.com/rollup/rollup/pull/3892): Add pull_request to windows github actions (@shellscape) +- [#3893](https://github.com/rollup/rollup/pull/3893): Update dependencies (@lukastaegert) +- [#3896](https://github.com/rollup/rollup/pull/3896): Replace deprecated folder package export with pattern export (@lukastaegert) + +## 2.34.0 + +_2020-11-29_ + +### Features + +- Support RequireJS comaptible AMD ids in code-splitting builds via amd.autoId (#3867) +- Allow adding an AMD id base path (#3867) + +### Bug Fixes + +- Warn when using an constant AMD id in a code-splitting build (#3867) + +### Pull Requests + +- [#3867](https://github.com/rollup/rollup/pull/3867): Implement amd.autoId/amd.basePath options (@tjenkinson) + +## 2.33.3 + +_2020-11-18_ + +### Bug Fixes + +- Do not use `.js` extension when importing AMD files from a UMD bundle (#3872) + +### Pull Requests + +- [#3861](https://github.com/rollup/rollup/pull/3861): Update chat/support links (@shellscape) +- [#3872](https://github.com/rollup/rollup/pull/3872): Also removeExtensionFromRelativeAmdId in UMD finaliser (@tjenkinson) + +## 2.33.2 + +_2020-11-14_ + +### Bug Fixes + +- Fix an issue where statements were ignored after a conditional return in a labeled statement (#3871) + +### Pull Requests + +- [#3871](https://github.com/rollup/rollup/pull/3871): Correctly track label usage in try statements (@Amareis) + +## 2.33.1 + +_2020-11-02_ + +### Bug Fixes + +- Add `syntheticNamedExports` to `this.getModuleInfo` to align with documentation (#3847) + +### Pull Requests + +- [#3847](https://github.com/rollup/rollup/pull/3847): Expose syntheticNamedExports to ModuleInfo (@Amareis) +- [#3852](https://github.com/rollup/rollup/pull/3852): Fix typo on docs (@jpsc) + +## 2.33.0 + +_2020-11-01_ + +### Features + +- Add parameter to "watchChange" hook to denote if a change was an addition, update or deletion (#3841) +- Add "closeWatcher" hook to allow plugins to clean up resources when the watcher is closed (#3841) +- Add "this.getWatchFiles" function to plugin context to get the current set of watched files (#3841) + +### Pull Requests + +- [#3841](https://github.com/rollup/rollup/pull/3841): Improved watcher hooks (@Amareis) +- [#3848](https://github.com/rollup/rollup/pull/3848): Add options hook to asyncpluginhooks (@intrnl) + +## 2.32.1 + +_2020-10-21_ + +### Bug Fixes + +- Print warning location for plugin warnings if only `loc` is supplied (#3824) + +### Pull Requests + +- [#3824](https://github.com/rollup/rollup/pull/3824): plugin warnings not showing warning.loc (@luciotato) + +## 2.32.0 + +_2020-10-16_ + +### Features + +- Extend `preserveEntrySignatures` with a value `"exports-only"` to allow extension only if an entry does not have exports (#3823) + +### Pull Requests + +- [#3823](https://github.com/rollup/rollup/pull/3823): Add "exports-only" option to preserveSignature (@lukastaegert) + +## 2.31.0 + +_2020-10-15_ + +### Features + +- When using the `output.moduleToStringTag` option, also add the tag to entries with exports and simulated external namespaces (#3822) +- Add the `__esModule` interop marker to IIFE global variables unless `output.esModule` is turned off (#3822) + +### Pull Requests + +- [#3822](https://github.com/rollup/rollup/pull/3822): Add module toStringTag to entries and interop namespaces (@lukastaegert) + +## 2.30.0 + +_2020-10-13_ + +### Features + +- Add `moduleParsed` hook that is called for each module once code and AST are available (#3813) +- Include code and AST in `this.getModuleInfo` (#3813) + +### Bug Fixes + +- Provide the original Acorn AST instead of the internal one when resolving dynamic imports that contain non-trivial expressions (#3813) + +### Pull Requests + +- [#3813](https://github.com/rollup/rollup/pull/3813): Add moduleParsed plugin hook (@lukastaegert) +- [#3815](https://github.com/rollup/rollup/pull/3815): Docs: wile => while (@tjenkinson) +- [#3817](https://github.com/rollup/rollup/pull/3817): Docs: fix code snippet (@codefrau) +- [#3818](https://github.com/rollup/rollup/pull/3818): Update documentation on configuring Babel, removing the section on passing '{"modules": false}' as that is no longer needed since Babel 7 (@Robin-Hoodie) + +## 2.29.0 + +_2020-10-08_ + +### Features + +- Allow passing custom options to other plugins via `this.resolve` (#3807) +- Allow attaching custom meta information to modules when resolving, loading or transforming (#3807) +- Do not throw but return `null` when using `this.getModuleInfo` for an unknown id (#3807) + +### Bug Fixes + +- Trigger build in watch mode when files are added to a watched directory (#3812) +- Make `code` optional when transforming modules (#3807) + +### Pull Requests + +- [#3807](https://github.com/rollup/rollup/pull/3807): Implement new APIs for inter-plugin communication (@lukastaegert) +- [#3808](https://github.com/rollup/rollup/pull/3808): Document that the default value of --format is 'es' (@jameshfisher) +- [#3812](https://github.com/rollup/rollup/pull/3812): Watch: listen for new files added to a directory (@dmitrage) + +## 2.28.2 + +_2020-09-24_ + +### Bug Fixes + +- Fix a source of possible variable name conflicts when using preserveModules with SystemJS (#3796) + +### Pull Requests + +- [#3792](https://github.com/rollup/rollup/pull/3792): add documentation for output.PreserveModulesRoot (@davidroeca) +- [#3796](https://github.com/rollup/rollup/pull/3796): Fix SystemJS default variable conflict (@lukastaegert) + +## 2.28.1 + +_2020-09-21_ + +### Bug Fixes + +- Fix a path slash issue when using the preserveModulesRoot option on Windows (#3791) + +### Pull Requests + +- [#3791](https://github.com/rollup/rollup/pull/3791): Fix preserveModulesRoot path on Windows (@lukastaegert) + +## 2.28.0 + +_2020-09-21_ + +### Features + +- Add an option to treat modules at a given path as located at root when preserving modules (#3786) + +### Pull Requests + +- [#3786](https://github.com/rollup/rollup/pull/3786): Add preserveModulesRoot config option (@davidroeca) + +## 2.27.1 + +_2020-09-17_ + +### Bug Fixes + +- Do not fail when using ES module imports in symlinked config files (#3783) + +### Pull Requests + +- [#3783](https://github.com/rollup/rollup/pull/3783): Handle loading symlinked config files (@lukastaegert) + +## 2.27.0 + +_2020-09-16_ + +### Features + +- Support specifying a file extension when reading from stdin (#3775) + +### Bug Fixes + +- Do not break logic if a branch with hoisted variables is tree-shaken in an else-if statement (#3782) + +### Pull Requests + +- [#3770](https://github.com/rollup/rollup/pull/3770): Docs: Exception for babel plugin and commonjs plugin (@jsk7) +- [#3775](https://github.com/rollup/rollup/pull/3775): add ability to specify stdin file extension via --stdin=ext (@kzc) +- [#3782](https://github.com/rollup/rollup/pull/3782): Handle hoisted variables in dead branches of nested if statements (@lukastaegert) + +## 2.26.11 + +_2020-09-08_ + +### Bug Fixes + +- Do not fail for unknown nodes as if statement branches (#3769) + +### Pull Requests + +- [#3769](https://github.com/rollup/rollup/pull/3769): Handle debugger statements as if-statement branches (@lukastaegert) + +## 2.26.10 + +_2020-09-04_ + +### Bug Fixes + +- Do not create invalid code when simplifying expressions in return statements that contain line comments (#3762) + +### Pull Requests + +- [#3757](https://github.com/rollup/rollup/pull/3757): Fix api docs loadconfigfile (@maxwell8888) +- [#3762](https://github.com/rollup/rollup/pull/3762): Handle line-comments when removing line-breaks to prevent ASI (@lukastaegert) + +## 2.26.9 + +_2020-09-01_ + +### Bug Fixes + +- Add regular expression support to watch include/exclude types (#3754) + +### Pull Requests + +- [#3754](https://github.com/rollup/rollup/pull/3754): Add RegExp to the include and exclude fields of the WatcherOptions type (@dagda1) +- [#3756](https://github.com/rollup/rollup/pull/3756): Update FAQ: I think it was meant "external" instead of "other-entry.js" (@madacol) + +## 2.26.8 + +_2020-08-29_ + +### Bug Fixes + +- Make sure that both unresolved and resolved ids are passed to the `external` option in all cases (#3753) + +### Pull Requests + +- [#3753](https://github.com/rollup/rollup/pull/3753): Also pass resolved ids to external if they use the object for (@lukastaegert) + +## 2.26.7 + +_2020-08-28_ + +### Bug Fixes + +- Avoid invalid code when rendering hoisted variable declarations from dead branches (#3752) +- Mark the `options` parameter of `this.parse` as optional for TypeScript plugins (#3750) + +### Pull Requests + +- [#3750](https://github.com/rollup/rollup/pull/3750): Make `options` of `PluginContext#parse` optional (@intrnl) +- [#3752](https://github.com/rollup/rollup/pull/3752): Extract hoisted variables from dead branches (@lukastaegert) + +## 2.26.6 + +_2020-08-27_ + +### Bug Fixes + +- Avoid conflicts between the namespace of synthetic named exports and local variables (#3747) + +### Pull Requests + +- [#3747](https://github.com/rollup/rollup/pull/3747): Properly deconflict synthetic named exports (@lukastaegert) + +## 2.26.5 + +_2020-08-22_ + +### Bug Fixes + +- Use correctly deconflicted variable names for reexported namespaces in ES formats (#3742) + +### Pull Requests + +- [#3742](https://github.com/rollup/rollup/pull/3742): Avoid variable name conflict when reexporting several namespaces from a chunk (@lukastaegert) + +## 2.26.4 + +_2020-08-19_ + +### Bug Fixes + +- Fix a situation where invalid code was rendered when dynamically importing a module with synthetic named exports when preserving modules (#3738) +- Create a proper namespace object when in a non-es format, a namespace is imported from a chunk with `default` export mode (#3738) +- Use the same variable when in a chunk, a namespace is both imported and reexported as a binding (#3738) +- Do not include the synthetic namespace in static entry points unless it is actually used (#3738) +- Make sure the chunking of one output does not interfere with the namespace objects of another output (#3738) + +### Pull Requests + +- [#3738](https://github.com/rollup/rollup/pull/3738): Improve synthetic entry handling (@lukastaegert) + +## 2.26.3 + +_2020-08-16_ + +### Bug Fixes + +- Fix a situation where line-breaks in a nested simplified conditional expression could result in broken code (#3734) + +### Pull Requests + +- [#3734](https://github.com/rollup/rollup/pull/3734): Prevent ASI when simplifying a nested logical expression (@lukastaegert) + +## 2.26.2 + +_2020-08-16_ + +### Bug Fixes + +- Fix a situation where line-breaks in a simplified conditional expression could result in broken code (#3732) + +### Pull Requests + +- [#3732](https://github.com/rollup/rollup/pull/3732): Prevent unintended ASI for nested conditionals (@lukastaegert) + +## 2.26.1 + +_2020-08-16_ + +### Bug Fixes + +- Correctly render external namespace imports when only generating SystemJS output (#3731) + +### Pull Requests + +- [#3731](https://github.com/rollup/rollup/pull/3731): Render system namespace import (@sastan and @lukastaegert) + +## 2.26.0 + +_2020-08-15_ + +### Features + +- Add a new entry `importedBindings` to the bundle information to list bindings per dependency (#3722) + +### Bug Fixes + +- Do not render an invalid UMD wrapper when no bindings are imported from a dependency (#3724) +- Avoid situations where removing the `else` branch from an `if` statement might catch the `else` branch from another one (#3725) + +### Pull Requests + +- [#3722](https://github.com/rollup/rollup/pull/3722): Add import specifiers to bundle information (@lukastaegert) +- [#3724](https://github.com/rollup/rollup/pull/3724): Fix missing variables for UMD and IIFE builds (@lukastaegert) +- [#3725](https://github.com/rollup/rollup/pull/3725): Do not entirely remove else branch if another else branch might accidentally be referenced (@lukastaegert) + +## 2.25.0 + +_2020-08-14_ + +### Features + +- Add `--failAfterWarnings` CLI flag that will complete builds with warnings but return an error at the end (#3712) + +### Pull Requests + +- [#3712](https://github.com/rollup/rollup/pull/3712): Implement `--failAfterWarnings` flag (@tjenkinson) + +## 2.24.0 + +_2020-08-13_ + +### Features + +- Allow defining interop per dependency via a function (#3710) +- Support interop "auto" as a more compatible version of "true" (#3710) +- Support interop "default" and "esModule" to avoid unnecessary interop helpers (#3710) +- Support interop "defaultOnly" for simplified helpers and Node ESM interop compatible output (#3710) +- Respect interop option for external dynamic imports (#3710) +- Support live-bindings for external default imports in non-ES formats unless "externalLiveBindings" is "false" (#3710) +- Use shared default interop helpers for AMD, UMD and IIFE formats (#3710) +- Avoid unnecessarily deconflicted module variables in non-ES formats (#3710) +- Freeze generated interop namespace objects (#3710) +- Always mark interop helpers as pure (#3710) +- Avoid default export interop if there is already an interop namespace object (#3710) +- Sort all `require` statements to the top in CommonJS output for easier back-transpilation to ES modules by other tools (#3710) + +### Bug Fixes + +- Handle accessing `super` in static class fields (#3720) +- Deconflict the names of helper variables introduced for interop (#3710) +- Generate proper namespace objects for static namespace imports in non-ES formats (#3710) +- Do not add unused interop helpers when using the renderDynamicImport hook (#3710) + +### Pull Requests + +- [#3710](https://github.com/rollup/rollup/pull/3710): Rework interop handling (@lukastaegert) +- [#3720](https://github.com/rollup/rollup/pull/3720): Handle super in static class fields (@lukastaegert) + +## 2.23.1 + +_2020-08-07_ + +### Bug Fixes + +- Fix an issue where dynamically importing an entry point could return a malformed namespace for CJS and AMD formats (#3709) + +### Pull Requests + +- [#3709](https://github.com/rollup/rollup/pull/3709): Properly construct namespace when dynamically importing chunks with facades in default export mode (@lukastaegert) + +## 2.23.0 + +_2020-07-23_ + +### Features + +- Handle environments with only globalThis in UMD output (#3691) + +### Pull Requests + +- [#3691](https://github.com/rollup/rollup/pull/3691): Check for globalThis in UMD wrapper (@lukastaegert) + +## 2.22.2 + +_2020-07-21_ + +### Bug Fixes + +- Always generate correct exports when an implicit entry is reexporting from another module (#3688) + +### Pull Requests + +- [#3688](https://github.com/rollup/rollup/pull/3688): Include all relevant modules to generate reexports for implicit dependencies (@lukastaegert) + +## 2.22.1 + +_2020-07-18_ + +### Bug Fixes + +- Remove unused arguments when calling a conditional expression (#3680) + +### Pull Requests + +- [#3680](https://github.com/rollup/rollup/pull/3680): Allow tree-shaking of arguments of functions that are returned by conditional expressions (@lukastaegert) + +## 2.22.0 + +_2020-07-18_ + +### Features + +- Allow resolving synthetic named exports via an arbitrary export name (#3657) +- Display a warning when the user does not explicitly select an export mode and would generate a chunk with default export mode when targeting CommonJS (#3657) + +### Pull Requests + +- [#3657](https://github.com/rollup/rollup/pull/3657): Add basic support for using a non-default export for syntheticNamedExports (@lukastaegert) +- [#3659](https://github.com/rollup/rollup/pull/3659): Warn when implicitly using default export mode (@lukastaegert) + +## 2.21.0 + +_2020-07-07_ + +### Features + +- Allow plugins to disable tree-shaking for individual modules to ensure even empty modules are associated with chunks (#3663) + +### Pull Requests + +- [#3663](https://github.com/rollup/rollup/pull/3663): Disable treeshaking per module (@lukastaegert) + +## 2.20.0 + +_2020-07-06_ + +### Features + +- Support using a function to generate different chunk and asset naming patterns per chunk or asset (#3658) +- Add `referencedFiles` property to the chunk info in generateBundle to list referenced assets (#3661) + +### Pull Requests + +- [#3658](https://github.com/rollup/rollup/pull/3658): Add ability to use a function that returns a pattern string in all places where you could use a pattern string before (@frank-dspeed) +- [#3661](https://github.com/rollup/rollup/pull/3661): Add referenced files to bundle (@lukastaegert) + +## 2.19.0 + +_2020-07-05_ + +### Features + +- Allow plugins to return a Promise in the options hook (#3660) + +### Pull Requests + +- [#3660](https://github.com/rollup/rollup/pull/3660): Make options hooks async (@TomerAberbach) + +## 2.18.2 + +_2020-07-02_ + +### Bug Fixes + +- Do not remove spread element args when the corresponding positional parameter is unused (#3652) + +### Pull Requests + +- [#3652](https://github.com/rollup/rollup/pull/3652): Do not tree-shake arguments that contain a spread element (@lukastaegert) + +## 2.18.1 + +_2020-06-26_ + +### Bug Fixes + +- Make sure synthetic exports are present when a module is imported dynamically (#3648) +- Strip the `rollup-plugin-` prefix off the plugin name when looking for the plugin export in a CLI plugin without a default export (#3647) +- Convert plugin names with dashes to camel case when looking for the plugin export in a CLI plugin without a default export (#3647) + +### Pull Requests + +- [#3647](https://github.com/rollup/rollup/pull/3647): Strip rollup-plugin prefix to find named plugin exports, throw when export cannot be found (@lukastaegert) +- [#3648](https://github.com/rollup/rollup/pull/3648): Always create a dynamic namespace object when a module with synthetic named exports is imported dynamically (@lukastaegert) + +## 2.18.0 + +_2020-06-22_ + +### Features + +- `inlineDynamicImports`, `manualChunks` and `preserveModules` can now be used as output options (#3645) +- Use sourcemaps for certain warnings that reference source code locations (#3645) + +### Bug Fixes + +- `this.getFileName` will now always return the correct file name for chunks when multiple outputs are created (#3645) + +### Pull Requests + +- [#3645](https://github.com/rollup/rollup/pull/3645): Per output chunking (@lukastaegert) + +## 2.17.1 + +_2020-06-19_ + +### Bug Fixes + +- Properly resolve accessing properties of namespace members again (#3643) + +### Pull Requests + +- [#3643](https://github.com/rollup/rollup/pull/3643): Fix accessing nested properties of namespaces (@lukastaegert) + +## 2.17.0 + +_2020-06-17_ + +### Features + +- When importing Rollup via package.exports, always fall back to the browser ESM build for non-Node environments (#3634) +- Create more efficient code when handling namespace mutations (#3637) + +### Bug Fixes + +- Fix a severe performance regression when the same module is imported by a lot of modules (#3641) +- Properly escape special characters in imports (#3638) + +### Pull Requests + +- [#3634](https://github.com/rollup/rollup/pull/3634): Set browser build in exports (@guybedford) +- [#3637](https://github.com/rollup/rollup/pull/3637): Do not include the whole namespace when illegally mutating a namespace (@lukastaegert) +- [#3638](https://github.com/rollup/rollup/pull/3638): Support backslash escaping, retain exact newline escaping (@guybedford) +- [#3641](https://github.com/rollup/rollup/pull/3641): Fix performance regression when a file is imported by many importers (@lukastaegert) + +## 2.16.1 + +_2020-06-13_ + +### Bug Fixes + +- Do not produce invalid code when an external or chunk id contain quotes or line-breaks (#3632) +- Do not fail but emit a warning when mutating a namespace object (#3633) + +### Pull Requests + +- [#3632](https://github.com/rollup/rollup/pull/3632): Handle single quote escaping in ids (@guybedford) +- [#3633](https://github.com/rollup/rollup/pull/3633): Turn namespace assignment error into a warning (@guybedford) + +## 2.16.0 + +_2020-06-12_ + +### Features + +- Add support for numeric separators (#3626) +- Switch to finalized ESTree optional chaining AST (#3628) + +### Pull Requests + +- [#3626](https://github.com/rollup/rollup/pull/3626): Support numeric separator (@TrySound) +- [#3628](https://github.com/rollup/rollup/pull/3628): Acorn 7.3.0 upgrade (@guybedford) +- [#3631](https://github.com/rollup/rollup/pull/3631): Improve discoverability of `manualChunks` for code splitting (@zlamma) + +## 2.15.0 + +_2020-06-08_ + +### Features + +- Allow to skip watching some configs via `watch: false` (#3620) +- Provide the resolved sourcemap path to `sourcemapPathTransform` (#3617) + +### Pull Requests + +- [#3617](https://github.com/rollup/rollup/pull/3617): Update sourcemapPathTransform to also take the path to the sourcemap file as a second argument (@dgoldstein0) +- [#3620](https://github.com/rollup/rollup/pull/3620): Rollup watch only one config in exported array (@luwol03) + +## 2.14.0 + +_2020-06-07_ + +### Features + +- Make `this.meta.watchMode` available for plugins to detect watch mode (#3616) + +### Bug Fixes + +- Handle exporting the same binding with different names in SystemJS (#3575) + +### Pull Requests + +- [#3575](https://github.com/rollup/rollup/pull/3575): Handle some cases of duplicate export bindings (@joeljeske) +- [#3616](https://github.com/rollup/rollup/pull/3616): Make watch mode available in plugins (@lukastaegert) + +## 2.13.1 + +_2020-06-04_ + +### Bug Fixes + +- Prevent conflicts in SystemJS when `module` is used as a top-level variable (#3614) + +### Pull Requests + +- [#3614](https://github.com/rollup/rollup/pull/3614): Handle system reserved identifier dedupes (@guybedford) + +## 2.13.0 + +_2020-06-03_ + +### Features + +- Allow to specify that an emitted chunk is only loaded after a given module has loaded to improve chunking (#3606) + +### Pull Requests + +- [#3606](https://github.com/rollup/rollup/pull/3606): Enable specifying implicit dependencies when emitting chunks (@lukastaegert) + +## 2.12.1 + +_2020-06-02_ + +### Bug Fixes + +- Render valid imports when chunk names correspond to directory names in virtual setups (#3609) + +### Pull Requests + +- [#3609](https://github.com/rollup/rollup/pull/3609): Handle imports from chunks with names that correspond to parent directory names of other chunks (@guybedford) + +## 2.12.0 + +_2020-05-31_ + +### Features + +- Add an option `--waitForBundleInput` to let the build wait until all entry point files are available before starting (#3577) + +### Pull Requests + +- [#3577](https://github.com/rollup/rollup/pull/3577): Wait for bundle input option (@Heerschop) + +## 2.11.2 + +_2020-05-28_ + +### Bug Fixes + +- Include side-effects in the second argument of `Array.from` (#3604) + +### Pull Requests + +- [#3604](https://github.com/rollup/rollup/pull/3604): Mark `Array.from` as side-effectful, use two-argument Array.from when mapping Sets (@lukastaegert) + +## 2.11.1 + +_2020-05-28_ + +### Bug Fixes + +- Also include side-effects in files that are marked as side-effect-free if they contain an included default export that is reexported (#3602) + +### Pull Requests + +- [#3602](https://github.com/rollup/rollup/pull/3602): Handle side-effects next to side-effect-free default exports in case the default export is reexported (@lukastaegert) + +## 2.11.0 + +_2020-05-27_ + +### Features + +- Add basic support for optional chaining (#3582) +- Provide a normalized set of options with proper default values to `buildStart` and `renderStart` (#3597) +- Do not count adding properties to the prototype of an unused class as a side-effect (#3598) +- Support providing `null` for empty setters in SystemJS via option (#3592) + +### Bug Fixes + +- Do not fail when using a `/*#__PURE__*/` annotation inside a class field (#3599) +- Allow using `--watch` and `--treeshake` together with sub-options such as `--watch.clearScreen` on the command line (#3597) + +### Pull Requests + +- [#3582](https://github.com/rollup/rollup/pull/3582): Support optional chaining via acorn fork(@guybedford) +- [#3592](https://github.com/rollup/rollup/pull/3592): System format optional setters(@guybedford) +- [#3597](https://github.com/rollup/rollup/pull/3597): Provide normalized options (@lukastaegert) +- [#3598](https://github.com/rollup/rollup/pull/3598): Treeshake prototype modifications in classes (@lukastaegert) +- [#3599](https://github.com/rollup/rollup/pull/3599): Retain pure annotations in class fields (@lukastaegert) +- [#3601](https://github.com/rollup/rollup/pull/3601): Fix white-space in docs (@tu4mo) + +## 2.10.9 + +_2020-05-24_ + +### Bug Fixes + +- Prevent invalid exports when facades are created (#3590) + +### Pull Requests + +- [#3590](https://github.com/rollup/rollup/pull/3590): Prevent unneeded exports when entry facades are created and ensure all exported variables in facades are imported (@lukastaegert) + +## 2.10.8 + +_2020-05-23_ + +### Bug Fixes + +- Fix issues when synthetic named exports are reexported as default exports (#3586) + +### Pull Requests + +- [#3584](https://github.com/rollup/rollup/pull/3584): Clarify documentation for `output.paths` (@jacksteamdev) +- [#3585](https://github.com/rollup/rollup/pull/3585): Target Node.js v14 instead of v13 in Windows tests (@mangs) +- [#3586](https://github.com/rollup/rollup/pull/3586): Handle default reexports of synthetic named exports over several stages (@lukastaegert) + +## 2.10.7 + +_2020-05-22_ + +### Bug Fixes + +- Handle modules re-exporting namespaces without further own code (#3576) + +### Pull Requests + +- [#3576](https://github.com/rollup/rollup/pull/3576): Fix "cannot read exports of undefined" error (@guybedford) + +## 2.10.6 + +_2020-05-22_ + +### Bug Fixes + +- Fix some issues around class fields (#3580) +- Prevent a maximum call stack error when a called entity references itself in its declaration (#3581) + +### Pull Requests + +- [#3580](https://github.com/rollup/rollup/pull/3580): Update acorn class features (@guybedford) +- [#3581](https://github.com/rollup/rollup/pull/3581): Do not fail when including call arguments of recursively defined variables (@lukastaegert) + +## 2.10.5 + +_2020-05-19_ + +### Bug Fixes + +- Do not remove side-effects that may influence an included default export declaration when side-effects are disabled (#3572) + +### Pull Requests + +- [#3572](https://github.com/rollup/rollup/pull/3572): Observe side-effects in files containing a default export declaration that reexports a variable (@lukastaegert) + +## 2.10.4 + +_2020-05-19_ + +### Bug Fixes + +- Tree-shake unused classes with fields unless there are side-effects in the field declaration (#3569) + +### Pull Requests + +- [#3569](https://github.com/rollup/rollup/pull/3569): Make sure unused classes with fields are tree-shaken if possible (@lukastaegert) + +## 2.10.3 + +_2020-05-18_ + +### Bug Fixes + +- Validate return value of sourcemapPathTransform option (#3561) + +### Pull Requests + +- [#3561](https://github.com/rollup/rollup/pull/3561): Throw error if sourcemapPathTransform-option does not return a string (@Simonwep) + +## 2.10.2 + +_2020-05-15_ + +### Bug Fixes + +- Properly include calls to mutating array methods in certain scenarios (#3559) + +### Pull Requests + +- [#3559](https://github.com/rollup/rollup/pull/3559): Make sure UnknownFooExpressions are included when referenced as return values in a MultiExpression (@lukastaegert) + +## 2.10.1 + +_2020-05-15_ + +### Bug Fixes + +- Do not throw when "undefined" is used as a default export (#3558) + +### Pull Requests + +- [#3558](https://github.com/rollup/rollup/pull/3558): Properly handle default exporting undefined (@lukastaegert) + +## 2.10.0 + +_2020-05-13_ + +### Features + +- Avoid unnecessary empty imports from a facade chunk to the original chunk (#3552) +- Pin facade creation order so that if several user-defined chunks reference the same module, the first always becomes the "actual" chunk while the later ones become facades (#3552) + +### Bug Fixes + +- Do not omit reexports from secondary chunks when creating facades for entry points without hoisting transitive dependencies (#3552) + +### Pull Requests + +- [#3552](https://github.com/rollup/rollup/pull/3552): Avoid unnecessary facade dependency inlining (@guybedford) + +## 2.9.1 + +_2020-05-11_ + +### Bug Fixes + +- Do not create unintended live-bindings or invalid reexports when reexporting global variables (#3550) + +### Pull Requests + +- [#3550](https://github.com/rollup/rollup/pull/3550): Track updates of globals that are exported as default (@lukastaegert) + +## 2.9.0 + +_2020-05-10_ + +### Features + +- Add ids of static and dynamic imports to `this.getModuleInfo` (#3542) +- Provide `getModuleInfo` and `getModuleIds` to `manualChunks` functions (#3542) +- Add nullish coalescing support (#3548) +- Make the rebuild delay in watch mode configurable and set the default to `0` for snappy rebuilds (#3502) +- Add `this.getModuleIds` to the plugin context as future replacement for `this.moduleIds` (#3542) + +### Pull Requests + +- [#3502](https://github.com/rollup/rollup/pull/3502): Configurable build delay (@mattdesl) +- [#3542](https://github.com/rollup/rollup/pull/3542): Extend manualChunks API (@lukastaegert) +- [#3548](https://github.com/rollup/rollup/pull/3548): Support nullish coalescing with tree-shaking (@lukastaegert) + +## 2.8.2 + +_2020-05-07_ + +### Bug Fixes + +- Avoid invalid code when simplifying the body of a shorthand arrow function expression (#3540) + +### Pull Requests + +- [#3540](https://github.com/rollup/rollup/pull/3540): Wrap object expressions in parentheses if they become children of an arrow function expression (@lukastaegert) + +## 2.8.1 + +_2020-05-07_ + +### Bug Fixes + +- Allow using plugins on CLI that are exported as `exports.default` (#3529) +- Do not fail side-effect detection in nested callbacks of builtins (#3539) + +### Pull Requests + +- [#3529](https://github.com/rollup/rollup/pull/3529): Use default named export with plugins (@NotWoods) +- [#3539](https://github.com/rollup/rollup/pull/3539): Track call side-effects both by entity and CallExpression to avoid untracked side-effects in nested calls (@lukastaegert) + +## 2.8.0 + +_2020-05-06_ + +### Features + +- When a dynamically imported chunk contains more exports than the imported module namespace, do not create a facade chunk but an inline namespace (#3535) + +### Bug Fixes + +- Do not execute dynamically imported code before synchronous code in the importing module when generating CommonJS (#3535) + +### Pull Requests + +- [#3535](https://github.com/rollup/rollup/pull/3535): Avoid dynamic facade chunks (@lukastaegert) + +## 2.7.6 + +_2020-04-30_ + +### Bug Fixes + +- Fix a type issue when a default export references a global variable (#3526) + +### Pull Requests + +- [#3526](https://github.com/rollup/rollup/pull/3526): Handles default exporting global variables (@lukastaegert) + +## 2.7.5 + +_2020-04-29_ + +### Bug Fixes + +- Prevent infinite loop when default values of function parameters in a default export contain a slash (#3522) + +### Pull Requests + +- [#3522](https://github.com/rollup/rollup/pull/3522): Avoid infinite loop when finding position for id insertion in default export (@lukastaegert) + +## 2.7.4 + +_2020-04-29_ + +### Bug Fixes + +- Fix an issue where wrong variable names were used when preserving modules (#3521) + +### Pull Requests + +- [#3521](https://github.com/rollup/rollup/pull/3521): Fix and improve default export alias logic (@lukastaegert) + +## 2.7.3 + +_2020-04-27_ + +### Bug Fixes + +- Do not access `__proto__` when running Rollup (#3518) + +### Pull Requests + +- [#3518](https://github.com/rollup/rollup/pull/3518): use acorn-class-fields and acorn-static-class-features from npm (@nitsky) + +## 2.7.2 + +_2020-04-22_ + +### Bug Fixes + +- Prevent an infinite loop when creating separate manual chunks with circular dependencies (#3510) +- Do not fail if "super" is used in the definition of a class field (#3511) +- Throw if a plugin tries to emit a file with an absolute Windows path (#3509) + +### Pull Requests + +- [#3509](https://github.com/rollup/rollup/pull/3509): Ban emitFile via absolute paths on Windows OS (@SASUKE40) +- [#3510](https://github.com/rollup/rollup/pull/3510): Do not fail for circular imports between manual chunks (@lukastaegert) +- [#3511](https://github.com/rollup/rollup/pull/3511): Support "super" in class fields (@lukastaegert) + +## 2.7.1 + +_2020-04-21_ + +### Bug Fixes + +- Use correct path for dynamic imports if `output.paths` is used (#3508) + +### Pull Requests + +- [#3508](https://github.com/rollup/rollup/pull/3508): Respect output.paths in dynamic imports (@lukastaegert) + +## 2.7.0 + +_2020-04-21_ + +### Features + +- Add `preserveEntrySignatures` option to control how exports of entry points are handled (#3498) +- Add `preserveSignature` flag to `this.emitFile` to control exports of emitted chunks (#3498) +- Add `output.minifyInternalExports` option to control if internal exports are minified (#3498) + +### Pull Requests + +- [#3498](https://github.com/rollup/rollup/pull/3498): Add option to configure if entry signatures are preserved (@lukastaegert) + +## 2.6.1 + +_2020-04-12_ + +### Bug Fixes + +- Close watch mode when stdin closes in a non-TTY environment (#3493) + +### Pull Requests + +- [#3493](https://github.com/rollup/rollup/pull/3493): Ensure --watch mode exits correctly when stdin is closed (@jakesgordon) + +## 2.6.0 + +_2020-04-10_ + +### Features + +- Allow regular expressions to declare external modules (#3482) + +### Pull Requests + +- [#3482](https://github.com/rollup/rollup/pull/3482): Allow regular expressions in config.external (@johannes-z) + +## 2.5.0 + +This version is identical to 2.4.0 + +## 2.4.0 + +_2020-04-09_ + +### Features + +- Add support for most private and public class field features (#3488) + +### Bug Fixes + +- Do not replace `this` with `undefined` in class field definitions (#3488) + +### Pull Requests + +- [#3488](https://github.com/rollup/rollup/pull/3488): Rollup class fields support (@guybedford and @lukastaegert) + +## 2.3.5 + +_2020-04-09_ + +### Bug Fixes + +- Never remove labels when tree-shaking is disabled (#3492) + +### Pull Requests + +- [#3492](https://github.com/rollup/rollup/pull/3492): Always use a new inclusion context when including declarations of variables, always inlcude labels when not treeshaking (@lukastaegert) + +## 2.3.4 + +_2020-04-07_ + +### Bug Fixes + +- Handle re-exporting synthetic exports from entry-points (#3319) +- Fix cross-chunk imports of synthetic exports (#3319) +- Handle namespace objects that contain re-exported synthetic namespaces (#3319) + +### Pull Requests + +- [#3319](https://github.com/rollup/rollup/pull/3319): Handle re-exports of synthetic named exports (@manucorporat and @lukastaegert) + +## 2.3.3 + +_2020-04-04_ + +### Bug Fixes + +- Add external namespaces to dynamic namespace objects (#3474) + +### Pull Requests + +- [#3474](https://github.com/rollup/rollup/pull/3474): Support external star exports on namespace objects (@guybedford) + +## 2.3.2 + +_2020-03-31_ + +### Bug Fixes + +- Only warn but do not fail build when a namespace is called as a function (#3475) +- Make sure pre-existing sourcemap comments are also removed when rebuilding using the cache (#3476) + +### Pull Requests + +- [#3475](https://github.com/rollup/rollup/pull/3475): Call namespace error as a warning (@guybedford) +- [#3476](https://github.com/rollup/rollup/pull/3476): Store locations for removed comments in cache (@lukastaegert) + +## 2.3.1 + +_2020-03-30_ + +### Bug Fixes + +- Do not fail if the config file returns an function returning a Promise (#3472) + +### Pull Requests + +- [#3472](https://github.com/rollup/rollup/pull/3472): Fix support for async functions as config (@lukastaegert) + +## 2.3.0 + +_2020-03-29_ + +### Features + +- Do not transpile config files with `.mjs` extension in Node 13+ or `.cjs` extension in any Node version and load them appropriately (#3445) +- Extract helper to load a config file the way rollup does it via `rollup/dist/loadConfigFile` (#3445) + +### Bug Fixes + +- Keep watching the config file if an error occurs during initial load in watch node (#3445) +- Add a helpful error message when using a transpiled config in a repository with "type": "module" (#3445) + +### Pull Requests + +- [#3445](https://github.com/rollup/rollup/pull/3445): Support native ESM configs in Node 13, support untranspiled configs (@lukastaegert) +- [#3468](https://github.com/rollup/rollup/pull/3468): Don't use esm output format alias in the documentation (@vsn4ik) + +## 2.2.0 + +_2020-03-24_ + +### Features + +- Add `renderDynamicImport` hook to rewrite dynamic import expressions (#3449) +- Add information about dynamically imported modules to `this.getModuleInfo` (#3449) + +### Bug Fixes + +- Make file emission work with Uin8Array sources when using Rollup in the browser (#3452) +- Fix types to allow watch to accept an array of configs (#3453) +- Do not strip `.js` extensions from AMD imports when the import is a user-supplied replacement for a non-resolvable dynamic import target (#3453) + +### Pull Requests + +- [#3449](https://github.com/rollup/rollup/pull/3449): Add hook to rewrite dynamic import expressions (@lukastaegert) +- [#3452](https://github.com/rollup/rollup/pull/3452): Avoid the assumption of Buffer in browser envs (@JoviDeCroock) +- [#3453](https://github.com/rollup/rollup/pull/3453): fix types since watch accepts single or array config (@lukeed) +- [#3456](https://github.com/rollup/rollup/pull/3456): fix SystemJS url in tutorial (@guybedford) + +## 2.1.0 + +_2020-03-18_ + +### Features + +- Allow specifying an importer when emitting files to resolve relative ids (#3442) + +### Pull Requests + +- [#3442](https://github.com/rollup/rollup/pull/3442): Add optional `importer` parameter to `this.emitFile` (@lukastaegert) + +## 2.0.6 + +_2020-03-13_ + +### Bug Fixes + +- Do not use file names from different outputs when generating sourcemaps using the `dir` option (#3440) + +### Pull Requests + +- [#3440](https://github.com/rollup/rollup/pull/3440): Use correct file names when writing sourcemaps for multiple outputs (@lukastaegert) + +## 2.0.5 + +_2020-03-12_ + +### Bug Fixes + +- Fix an issue where conditional statements would assume they have the wrong test value (#3438) + +### Pull Requests + +- [#3438](https://github.com/rollup/rollup/pull/3438): Make sure logical expressions always check the left argument for side-effects (@lukastaegert) + +## 2.0.4 + +_2020-03-12_ + +### Bug Fixes + +- Avoid conflicts between namespace imports when preserving modules (#3435) + +### Pull Requests + +- [#3435](https://github.com/rollup/rollup/pull/3435): Deconflict multiple `index` imports for ES format using nested export star statements (@kamranayub) + +## 2.0.3 + +_2020-03-10_ + +### Bug Fixes + +- Add type for this.getCombinedSourcemap to transform context (#3431) + +### Pull Requests + +- [#3377](https://github.com/rollup/rollup/pull/3377): Switch to yargs-parser lib (@jamesgeorge007) +- [#3426](https://github.com/rollup/rollup/pull/3426): Use strict types with PluginDriver (@NotWoods) +- [#3431](https://github.com/rollup/rollup/pull/3431): Add missing type declaration for getCombinedSourcemap (@Anidetrix) +- [#3432](https://github.com/rollup/rollup/pull/3432): Detail how return values from `augmentChunkHash` are used (@jakearchibald) + +## 2.0.2 + +_2020-03-07_ + +### Bug Fixes + +- Make sure the ESM import still works (#3430) + +### Pull Requests + +- [#3430](https://github.com/rollup/rollup/pull/3430): Fix conditional exports again (@lukastaegert) + +## 2.0.1 + +_2020-03-07_ + +### Bug Fixes + +- Reenable importing rollup in Node 13.0 - 13.7 (#3428) + +### Pull Requests + +- [#3428](https://github.com/rollup/rollup/pull/3428): Fix conditional exports in Node 13.0 - 13.7 (@lukastaegert) + +## 2.0.0 + +_2020-03-06_ + +### Breaking Changes + +- Rollup now requires at least Node 10 to run, or a sufficiently modern browser (#3346) +- The file structure of Rollup's ESM builds has changed: + + - The main ESM entry point is now at `rollup/dist/es/rollup.js` instead of `rollup/dist/rollup.es.js` + - The ESM browser build is at `rollup/dist/es/rollup.browser.js` instead of `rollup/dist/rollup.browser.es.js` + + In general, the ESM builds now follow the same naming scheme as the CJS builds but are located in the `rollup/dist/es` subfolder instead of `rollup/dist` (#3391) + +- The "watch.chokidar" option no longer accepts a `boolean` value but only an object of parameters that is passed to the bundled Chokidar instance. Chokidar installations by the user will be ignored in favour of the bundled instance (#3331) +- Modules that are completely tree-shaken will no longer be listed as part of any chunks in `generateBundle` +- The `experimentalOptimizeChunks` and `chunkGroupingSize` options have been removed +- [acorn](https://github.com/acornjs/acorn) plugins can only be used if they accept a passed-in acorn instance instead of importing it themselves. See https://github.com/acornjs/acorn/pull/870#issuecomment-527339830 for what needs to be done to make plugins compatible that do not support this yet (#3391) +- Emitted chunks now have the TypeScript type `Uint8Array` instead of `Buffer`. A `Buffer` can still be used, though (#3395) +- The TypeScript types no longer use ESTree types for AST nodes but a very generic type that does not contain information specific to certain node types (#3395) +- The signature of the `writeBundle` plugin hook has been changed to match `generateBundle`: The bundle object is now passed as second parameter instead of first and the first parameter is the output options (#3361) +- The following plugin hooks have been removed: + - ongenerate: use `generateBundle` instead + - onwrite: use `writeBundle` instead + - transformBundle: use `renderChunk` instead + - transformChunk: use `renderChunk` instead +- You can no longer access `this.watcher` on the plugin context. +- The `transform` hook can no longer return `dependencies`. +- The `treeshake.pureExternalModules` option will now show a deprecation warning when used: use `treeshake.moduleSideEffects: 'no-external'` instead +- Using `import.meta.ROLLUP_ASSET_URL_<..>` and `import.meta.ROLLUP_CHUNK_URL_<..>` in code will now show warnings: use `import.meta.ROLLUP_FILE_URL_<..>` instead +- The `resolveAssetUrl` hook will now show a deprecation warning when used: use `resolveFileUrl` instead +- The following plugin context functions will show warnings when used: + - `this.emitAsset`: use `this.emitFile` + - `this.emitChunk`: use `this.emitFile` + - `this.getAssetFileName`: use `this.getFileName` + - `this.getChunkFileName`: use `this.getFileName` + - `this.isExternal`: use `this.resolve` + - `this.resolveId`: use `this.resolve` +- Directly adding properties to the bundle object in the `generateBundle` is deprecated will show a warning (removing properties is allowed, though): Use `this.emitFile` +- Accessing `chunk.isAsset` on the bundle is deprecated: Use `chunk.type === 'asset'` instead +- The error code for a missing `name` property when targeting UMD has been changed to `MISSING_NAME_OPTION_FOR_IIFE_EXPORT` to emphasize this is needed for the IIFE part of UMD (#3393) + +### Features + +- Rollup now bundles [Chokidar](https://github.com/paulmillr/chokidar) for a better watch experience (#3331) +- Rollup now bundles [acorn](https://github.com/acornjs/acorn) again, removing its only external dependency (#3391) +- Do not consider empty imports from side-effect-free modules for chunking and hoist side-effect imports if necessary (#3369) +- Rollup can now be imported as an ES module in Node via `import {rollup} from 'rollup'`. Note that this relies on Node's experimental [conditional package exports](https://nodejs.org/dist/latest-v13.x/docs/api/esm.html#esm_conditional_exports) feature and is therefore itself experimental (#3391) +- `systemjs` can be used as format alias for `system` (#3381) + +### Bug Fixes + +- Unknown output options now trigger a warning when using the JavaScript API (#3352) +- Rollup will no longer introduce Node types into TypeScript projects that do not use them (#3395) +- Generate correct sourcemaps when tree-shaking occurs in a multi-file bundle (#3423) + +### Pull Requests + +- [#3331](https://github.com/rollup/rollup/pull/3331): Bundle Chokidar (@lukastaegert) +- [#3343](https://github.com/rollup/rollup/pull/3343): Remove experimentalOptimizeChunks (@lukastaegert) +- [#3346](https://github.com/rollup/rollup/pull/3346): Update minimum required Node version to 10 (@lukastaegert) +- [#3352](https://github.com/rollup/rollup/pull/3352): Remove active deprecations (@lukastaegert) +- [#3361](https://github.com/rollup/rollup/pull/3361): Change writeBundle signature to match generateBundle (@lukastaegert) +- [#3369](https://github.com/rollup/rollup/pull/3369): Avoid empty imports from side-effect-free chunks (@lukastaegert) +- [#3381](https://github.com/rollup/rollup/pull/3381): Rename esm to es everywhere, add systemjs alias (@lukastaegert) +- [#3391](https://github.com/rollup/rollup/pull/3391): Bundle acorn, allow importing Rollup as Node ES module, update dependencies (@lukastaegert) +- [#3393](https://github.com/rollup/rollup/pull/3393): Better error code for name-less umd bundle (@rail44) +- [#3395](https://github.com/rollup/rollup/pull/3395): Remove `@types` dependencies (@lukastaegert) +- [#3423](https://github.com/rollup/rollup/pull/3423): Update magic-string and fix sourcemaps (@lukastaegert) + +## 1.32.1 + +_2020-03-06_ + +### Bug Fixes + +- Handle default export detection for AMD and IIFE externals that do not have a prototype (#3420) +- Handle missing whitespace when the else branch of an if-statement is simplified (#3421) +- Mention the importing module when reporting errors for missing named exports (#3401) +- Add code to warning for missing output.name of IIFE bundles (#3372) + +### Pull Requests + +- [#3372](https://github.com/rollup/rollup/pull/3372): Add warning code for missing output.name of IIFE bundle that has export (@rail44) +- [#3401](https://github.com/rollup/rollup/pull/3401): Missing exports errors now print the importing module (@timiyay) +- [#3418](https://github.com/rollup/rollup/pull/3418): Structure lifecycle hooks, add links to build time hooks (@lukastaegert) +- [#3420](https://github.com/rollup/rollup/pull/3420): Update generated code of getInteropBlock() to work with null prototype objects (@jdalton) +- [#3421](https://github.com/rollup/rollup/pull/3421): Avoid invalid code when "else" branch is simplified (@lukastaegert) + +## 1.32.0 + +_2020-02-28_ + +### Features + +- Allow adding plugins on the command line via `--plugin ` (#3379) + +### Pull Requests + +- [#3379](https://github.com/rollup/rollup/pull/3379): introduce CLI --plugin support (@kzc) +- [#3390](https://github.com/rollup/rollup/pull/3390): fix typo: this.addWatchfile (@mistlog) +- [#3392](https://github.com/rollup/rollup/pull/3392): Bump codecov from 3.6.1 to 3.6.5 +- [#3404](https://github.com/rollup/rollup/pull/3404): Update resolveFileUrl docs (@jakearchibald) + +## 1.31.1 + +_2020-02-14_ + +### Bug Fixes + +- Make sure errored files are always re-evaluated in watch mode to avoid an issue in the typescript plugin (#3388) + +### Pull Requests + +- [#3366](https://github.com/rollup/rollup/pull/3366): Correct spelling minifaction to minification (@VictorHom) +- [#3371](https://github.com/rollup/rollup/pull/3371): Adjust bug template to mention REPL.it (@lukastaegert) +- [#3388](https://github.com/rollup/rollup/pull/3388): Run transform hooks again in watch mode on files that errored (@lukastaegert) + +## 1.31.0 + +_2020-01-31_ + +### Features + +- Always disable tree-shaking for asm.js functions to maintain semantics (#3362) + +### Pull Requests + +- [#3362](https://github.com/rollup/rollup/pull/3362): Preserve asm.js code (@lukastaegert) + +## 1.30.1 + +_2020-01-27_ + +### Bug Fixes + +- Do not mistreat static entgry points as dynamic ones when chunking (#3357) +- Resolve a crash when chunking circular dynamic imports (#3357) + +### Pull Requests + +- [#3357](https://github.com/rollup/rollup/pull/3357): Resolve issues with circular dynamic entries (@lukastaegert) + +## 1.30.0 + +_2020-01-27_ + +### Features + +- Do not split chunks when dynamically imported modules import modules that are already loaded by all dynamic importers (#3354) +- Add `hoistTransitiveImports` option to disable hoisting imports of static dependencies into entry chunks (#3353) + +### Bug Fixes + +- Make sure polyfills are always loaded first when each static entry point contains them as first import (#3354) + +### Pull Requests + +- [#3353](https://github.com/rollup/rollup/pull/3353): Add option to avoid hoisting transitive imports (@lukastaegert) +- [#3354](https://github.com/rollup/rollup/pull/3354): Improve chunking algorithm for dynamic imports (@tjenkinson and @lukastaegert) + +## 1.29.1 + +_2020-01-21_ + +### Bug Fixes + +- Avoid crashes for circular reexports when named exports cannot be found (#3350) + +### Pull Requests + +- [#3335](https://github.com/rollup/rollup/pull/3335): Fix typo (@robbinworks) +- [#3342](https://github.com/rollup/rollup/pull/3342): Remove ":" from test file names for Windows and update dependencies (@lukastaegert) +- [#3350](https://github.com/rollup/rollup/pull/3350): Properly handle circular reexports (@lukastaegert) + +## 1.29.0 + +_2020-01-08_ + +### Features + +- Enable top-level await by default (#3089) +- Add typings for watch events (#3302) + +### Bug Fixes + +- Deconflict files that would conflict only on a case-insensitive OS (#3317) +- Do not fail in certain scenarios where a logical expression inside a sequence expression was being directly included (#3327) + +### Pull Requests + +- [#3089](https://github.com/rollup/rollup/pull/3089): Move top-level await out of experimental (@guybedford) +- [#3302](https://github.com/rollup/rollup/pull/3302): Adds type definitions for RollupWatcher events (@NotWoods) +- [#3317](https://github.com/rollup/rollup/pull/3317): Fix module id conflict on a case insensitive OS (@yesmeck) +- [#3327](https://github.com/rollup/rollup/pull/3327): Handle deoptimizations while a node is being included (@lukastaegert) + +## 1.28.0 + +_2020-01-04_ + +### Features + +- Allow piping in stdin via the command line interface (#3312, #3290) +- Allow plugins to mark modules as having syntheticNamedExports for e.g. better CJS interoperability (#3295) +- Ignore variable reassignments in dead code when tree-shaking to remove more unneeded code (#3212) + +### Bug Fixes + +- Properly respect tree-shaken code when generating sourcemaps (#3318) + +### Pull Requests + +- [#3212](https://github.com/rollup/rollup/pull/3212): Handle assignments in dead code (@tjenkinson) +- [#3290](https://github.com/rollup/rollup/pull/3290): Implement stdin input with optional "-" as the file name (@kzc) +- [#3295](https://github.com/rollup/rollup/pull/3295): Add syntheticNamedExports (@manucorporat) +- [#3300](https://github.com/rollup/rollup/pull/3300): Add note about setting `types` in tsconfig file (@tjenkinson) +- [#3303](https://github.com/rollup/rollup/pull/3303): Use ! to assert not-null in TypeScript (@NotWoods) +- [#3312](https://github.com/rollup/rollup/pull/3312): Implement stdin input (@lukastaegert) +- [#3318](https://github.com/rollup/rollup/pull/3318): Update magic-string and other dependencies (@lukastaegert) + +## 1.27.14 + +_2019-12-22_ + +### Bug Fixes + +- Update references to official rollup plugins in error messages (#3297, #3298) + +### Pull Requests + +- [#3286](https://github.com/rollup/rollup/pull/3286): Update link to JavaScript API documentation (@romankaravia) +- [#3294](https://github.com/rollup/rollup/pull/3294): Update deprecated references to the node-resolve plugin in the documentation (@Vlad-Shcherbina) +- [#3297](https://github.com/rollup/rollup/pull/3297): Update references to rollup-plugin-json (@cprecioso) +- [#3298](https://github.com/rollup/rollup/pull/3298): Update references to official rollup plugins (@cprecioso) + +## 1.27.13 + +_2019-12-14_ + +### Bug Fixes + +- Do not truncate environment variable values at the first colon when using the `--environment` option (#3283) + +### Pull Requests + +- [#3283](https://github.com/rollup/rollup/pull/3283): Allow environment variables to contain colons (@tlaverdure) + +## 1.27.12 + +_2019-12-13_ + +### Bug Fixes + +- Prevent invalid AMD or SystemJS code when accessing `import.meta` (#3282) + +### Pull Requests + +- [#3282](https://github.com/rollup/rollup/pull/3282): Always make "module" available for SystemJS and AMD formats if `import.meta` is accessed directly (@lukastaegert) + +## 1.27.11 + +_2019-12-12_ + +### Bug Fixes + +- Resolve a crash due to an infinite loop (#3280) + +### Pull Requests + +- [#3280](https://github.com/rollup/rollup/pull/3280): Prevent infinite deoptimizations (@lukastaegert) + +## 1.27.10 + +_2019-12-11_ + +### Bug Fixes + +- Keep track of function return values in more situations (#3278) + +### Pull Requests + +- [#3278](https://github.com/rollup/rollup/pull/3278): Avoid some unnecessary value tracking deoptimizations (@lukastaegert) + +## 1.27.9 + +_2019-12-07_ + +### Bug Fixes + +- Fix an issue where reexports could be missing when preserving modules (#3273) +- Allow turning of color output via NO_COLOR or FORCE_COLOR=0 environment variables (#3272) + +### Pull Requests + +- [#3272](https://github.com/rollup/rollup/pull/3272): Support either NO_COLOR or FORCE_COLOR=0 to turn off color (@kikonen) +- [#3273](https://github.com/rollup/rollup/pull/3273): Make sure that indirectly reexported modules also become chunk dependencies when preserving modules(@lukastaegert) + +## 1.27.8 + +_2019-12-02_ + +### Bug Fixes + +- Deoptimize objects when a method is called on them to make sure modifications via "this" are observed (#3266) + +### Pull Requests + +- [#3266](https://github.com/rollup/rollup/pull/3266): Workaround for various object literal mutation bugs (@kzc) + +## 1.27.7 + +_2019-12-01_ + +### Bug Fixes + +- Fix a scenario where a reassignments to computed properties were not tracked (#3267) + +### Pull Requests + +- [#3267](https://github.com/rollup/rollup/pull/3267): Fix incomplete computed property deoptimization (@lukastaegert) + +## 1.27.6 + +_2019-11-30_ + +### Bug Fixes + +- Use "auto" export mode by default for all modules when preserving modules (#3265) +- Observe "output.exports" when preserving modules and warn for mixed exports if necessary (#3265) + +### Pull Requests + +- [#3265](https://github.com/rollup/rollup/pull/3265): Use export mode "auto" by default when preserving modules (@lukastaegert) + +## 1.27.5 + +_2019-11-25_ + +### Bug Fixes + +- Make sure namespaces for inlined dynamic imports are treated as variable accesses when deconflicting (#3256) + +### Pull Requests + +- [#3256](https://github.com/rollup/rollup/pull/3256): Avoid name conflicts when inlining dynamic imports nested in functions (@lukastaegert) +- [#3257](https://github.com/rollup/rollup/pull/3257): Update dependencies (@lukastaegert) + +## 1.27.4 + +_2019-11-22_ + +### Bug Fixes + +- Aggregate circular dependency warnings in the CLI (#3249) +- Do not defer non-aggregated handlers in the CLI (#3249) + +### Pull Requests + +- [#3249](https://github.com/rollup/rollup/pull/3249): Fix broken Windows CLI tests (@lukastaegert) +- [#3251](https://github.com/rollup/rollup/pull/3251): Add installation as a separate header (@ashrith-kulai) + +## 1.27.3 + +_2019-11-20_ + +### Bug Fixes + +- Provide better warning when empty chunks are created in a code-splitting scenario (#3244) + +### Pull Requests + +- [#3244](https://github.com/rollup/rollup/pull/3244): Clearer empty chunk warning (@tjenkinson) + +## 1.27.2 + +_2019-11-18_ + +### Bug Fixes + +- Fix an issue where live bindings were not working correctly when using `+=` in SystemJS (#3242) + +### Pull Requests + +- [#3242](https://github.com/rollup/rollup/pull/3242): Export updated assignments when using shorthand update assignment expressions in SystemJS (@lukastaegert) + +## 1.27.1 + +_2019-11-18_ + +### Bug Fixes + +- Fix an issue where code after a switch-statement with removed cases was erroneously not included (#3241) + +### Pull Requests + +- [#3237](https://github.com/rollup/rollup/pull/3237): make `acornOptions` optional in `parse()` in docs (@tjenkinson) +- [#3240](https://github.com/rollup/rollup/pull/3240): Update dependencies and fix vulnerability (@lukastaegert) +- [#3241](https://github.com/rollup/rollup/pull/3241): Do not truncate after switch-statement with removed case (@lukastaegert) + +## 1.27.0 + +_2019-11-12_ + +### Features + +- Add support for output-specific plugins (#3218) +- Reenable parallel output processing when using the CLI (#3218) +- Warn if files are emitted that would overwrite previously emitted files (#3218) + +### Bug Fixes + +- Do not overwrite files emitted in other builds if outputs are generated in parallel (#3218) + +### Pull Requests + +- [#3218](https://github.com/rollup/rollup/pull/3218): Per output plugins (@lukastaegert) + +## 1.26.5 + +_2019-11-11_ + +### Bug Fixes + +- Fix a regression where it was no longer to pass a certain option format to generate (#3223) + +### Pull Requests + +- [#3223](https://github.com/rollup/rollup/pull/3223): Allow passing input options to output (@lukastaegert) + +## 1.26.4 + +_2019-11-09_ + +### Bug Fixes + +- Keep watching known files after a plugin error during the initial build (#3219) + +### Pull Requests + +- [#3216](https://github.com/rollup/rollup/pull/3216): Fix small typo (@kaisermann) +- [#3217](https://github.com/rollup/rollup/pull/3217): Update dependencies and fix security vulnerability (@lukastaegert) +- [#3219](https://github.com/rollup/rollup/pull/3219): Also recover from plugin errors during the initial build (@lukastaegert) + +## 1.26.3 + +_2019-11-02_ + +### Bug Fixes + +- Work around an incompatibility with rollup-plugin-dts (#3211) + +### Pull Requests + +- [#3211](https://github.com/rollup/rollup/pull/3211): Do no fail if the source attribute is `undefined` in an unused named export (@lukastaegert) + +## 1.26.2 + +_2019-10-31_ + +### Bug Fixes + +- Do not create invalid code when using `treeshake: false` and star re-exports (#3209) + +### Pull Requests + +- [#3209](https://github.com/rollup/rollup/pull/3209): Also remove export-all declarations when not tree-shaking (@lukastaegert) + +## 1.26.1 + +_2019-10-31_ + +### Bug Fixes + +- Prevent an issue where outputs would overwrite files emitted by other outputs (#3201) +- Do not throw an error if the config file does not have a .js extension (#3204) + +### Pull Requests + +- [#3201](https://github.com/rollup/rollup/pull/3201): Make the CLI run generate/output in serial (@marijnh) +- [#3204](https://github.com/rollup/rollup/pull/3204): support all config file extensions (.js,.mjs,...) (@arlac77) + +## 1.26.0 + +_2019-10-27_ + +### Features + +- Only warn when no output is provided for an IIFE bundle but still produce valid code (#3181) +- Support reexporting namespaces as a binding (#3193) +- Switch from hash.js to crypto for hashing in the Node build for better performance and support for very large assets (#3194) + +### Bug Fixes + +- Correctly handle chunks reexporting the same namespace as two different bindings (#3193) + +### Pull Requests + +- [#3181](https://github.com/rollup/rollup/pull/3181): Remove the need to provide an output name for IIFE bundles (@bterrier) +- [#3193](https://github.com/rollup/rollup/pull/3193): Add support for "export \* as name from …" (@lukastaegert) +- [#3194](https://github.com/rollup/rollup/pull/3194): Add support for large assets (> 100 MB) (@SebastianNiemann) + +## 1.25.2 + +_2019-10-23_ + +### Bug Fixes + +- Improve performance of bundled UMD code by adding additional parentheses to enforce eager parsing (#3183) +- Improve types to tolerate passing a Rollup config with multiple outputs to `rollup.rollup` (#3184) + +### Pull Requests + +- [#3183](https://github.com/rollup/rollup/pull/3183): Add parentheses to factory function of UMD bundles (@ajihyf) +- [#3184](https://github.com/rollup/rollup/pull/3184): RollupOptions accept output as array (@imcotton) + +## 1.25.1 + +_2019-10-20_ + +### Bug Fixes + +- Handle a situation where code was not included after a switch statement (#3178) +- Handle a situation where code was not included after a do-while loop (#3180) +- Do not fail if different outputs emit the same file (#3175) +- Give access to the original acorn error for parse errors (#3176) + +### Pull Requests + +- [#3175](https://github.com/rollup/rollup/pull/3175): Disable errors for duplicate emitted file names (@marijnh) +- [#3176](https://github.com/rollup/rollup/pull/3176): Add original parser error to rollup error; Update tests (@gribnoysup) +- [#3178](https://github.com/rollup/rollup/pull/3178): Fix switch case not being included correctly (@lukastaegert) +- [#3179](https://github.com/rollup/rollup/pull/3179): Update dependencies (@lukastaegert) +- [#3180](https://github.com/rollup/rollup/pull/3180): Handle conditional breaks in do-while loops with unconditional return (@lukastaegert) + +## 1.25.0 + +_2019-10-18_ + +### Features + +- Remove try-catch if there is no side-effect in the try-block (#3166) +- Omit side-effect-free trailing cases in switch-statements (#3166) +- Remove unused labels (#3170) + +### Bug Fixes + +- Do not remove code after labeled statements that contain a throw or return if the label is used (#3170) +- Prevent invalid code when expressions are simplified that do not follow a white-space character (#3173) +- Do not remove continue statements inside switch statements (#3166) +- Prevent trailing empty lines when tree-shaking inside switch statements (#3166) + +### Pull Requests + +- [#3166](https://github.com/rollup/rollup/pull/3166): Better try statement tree shaking (@lukastaegert) +- [#3170](https://github.com/rollup/rollup/pull/3170): Handle optional control flow in labeled statements, remove unused labels (@lukastaegert) +- [#3173](https://github.com/rollup/rollup/pull/3173): Add missing spaces in certain statements and expressions to avoid invalid code (@lukastaegert) + +## 1.24.0 + +_2019-10-15_ + +### Features + +- Respect `break`, `continue`, `return` and `throw` when tree-shaking to detect dead code (#3153) +- Do treat treat hoisted function declarations as "unknown" when checking for call side-effects (#3153) + +### Bug Fixes + +- Make sure that unknown `import.meta` properties produce valid code in SystemJS (#3152) +- Make sure `treeshake.annotations: false` is respected for class instantiation (#3153) +- Check property access side-effects for class instantiation (#3153) +- Do not suppress break statements inside labeled statements (#3153) + +### Pull Requests + +- [#3152](https://github.com/rollup/rollup/pull/3152): Allow import.meta.\* for systemjs format (@dmail) +- [#3153](https://github.com/rollup/rollup/pull/3153): Get rid of immutable.js and implement tree-shaking for broken control flow (@lukastaegert) + +## 1.23.1 + +_2019-10-05_ + +### Bug Fixes + +- Fix a regression where the node types had a specific minimal version (#3143) + +### Pull Requests + +- [#3143](https://github.com/rollup/rollup/pull/3143): Ensure that types packages have star version ranges (@lukastaegert) + +## 1.23.0 + +_2019-10-03_ + +### Features + +- Add placeholders for extensions when preserving modules (#3116) + +### Pull Requests + +- [#3116](https://github.com/rollup/rollup/pull/3116): Include extensions in preserveModules output filenames for scriptified assets (@Andarist) +- [#3142](https://github.com/rollup/rollup/pull/3142): Fix typo (@tu4mo) + +## 1.22.0 + +_2019-09-29_ + +### Features + +- Add a new "hidden" sourcemap type that generates the map files but omits the sourcemap comment (#3120) +- Generate more efficient code when using `namespaceToStringTag: true` (#3135) +- Make sure namespace objects do not have a prototype (#3136) + +### Bug Fixes + +- Do not ignore side-effectful iterators by always preserving for..of loops for now (#3132) +- Make sure `--context` is observed as a CLI option (#3134) +- Do not require specific versions for @types dependencies (#3131) + +### Pull Requests + +- [#3120](https://github.com/rollup/rollup/pull/3120): Generate sourcemaps but omit the comment (@rohitmohan96) +- [#3131](https://github.com/rollup/rollup/pull/3131): Use asterisk for @types/\* dependencies (@frenzzy) +- [#3132](https://github.com/rollup/rollup/pull/3132): Preserve empty for...of loops (@imatlopez) +- [#3133](https://github.com/rollup/rollup/pull/3133): Update dependencies (@lukastaegert) +- [#3134](https://github.com/rollup/rollup/pull/3134): Wire up --context CLI flag (@tchetwin) +- [#3135](https://github.com/rollup/rollup/pull/3135): Remove Symbol polyfill in module namespaces (@mkubilayk) +- [#3136](https://github.com/rollup/rollup/pull/3136): Set null prototype on namespace objects (@rpamely) + +## 1.21.4 + +_2019-09-16_ + +### Bug Fixes + +- Recognize common browser globals (#3117) +- Do not treat "typeof " as a side-effect (#3117) + +### Pull Requests + +- [#3117](https://github.com/rollup/rollup/pull/3117): Add browser globals to known globals and prevent "typeof" side-effects (@lukastaegert) + +## 1.21.3 + +_2019-09-14_ + +### Bug Fixes + +- Fix a regression where modifying a watched file did not trigger a rebuild (#3112) + +### Pull Requests + +- [#3112](https://github.com/rollup/rollup/pull/3112): Fix .addWatchFile() dependencies failing to invalidate in watch mode (@tivac) + +## 1.21.2 + +_2019-09-09_ + +### Bug Fixes + +- Fix wrong deprecation message to direct to `this.emitFile` instead of `this.emitAsset` + +## 1.21.1 + +_2019-09-09_ + +### Bug Fixes + +- Allow legacy plugins to still add assets directly to the bundle object (#3105) + +### Pull Requests + +- [#3105](https://github.com/rollup/rollup/pull/3105): Allow legacy plugins to still add assets directly to the bundle object (@lukastaegert) + +## 1.21.0 + +_2019-09-08_ + +### Features + +- Respect `output.entryFileNames` when preserving modules (#3088) +- Make accessing unknown globals a side-effect unless this is deactivated via `treeshake.unknownGlobalSideEffects` (#3068) +- Respect global objects when checking for pure global functions (#3068) +- Introduce a `type` to more easily distinguish chunks and assets in the output bundle (#3080) + +### Bug Fixes + +- Recover in watch mode when the initial build fails (#3081) +- Make sure `output.strict` is respected for SystemJS output (#3101) + +### Pull Requests + +- [#3068](https://github.com/rollup/rollup/pull/3068): Make accessing unknown globals a side-effect (@lukastaegert) +- [#3080](https://github.com/rollup/rollup/pull/3080): OutputBundle Tagged union with 'type = chunk|asset' (@askbeka) +- [#3081](https://github.com/rollup/rollup/pull/3081): Watch files onbuild, even if build fails (@mhkeller) +- [#3088](https://github.com/rollup/rollup/pull/3088): Add support for entryFileNames pattern used in combination with preserveModules option (@Andarist) +- [#3101](https://github.com/rollup/rollup/pull/3101): Remove 'use strict'; from systemjs when strict=false (@askbeka) + +## 1.20.3 + +_2019-08-28_ + +### Bug Fixes + +- Make sure file hashes change when a change of the naming pattern leads to a file name change of a dependency (#3083) +- Fix several issues where reexporting an external "default" export could lead to invalid or incorrect code (#3084) + +### Pull Requests + +- [#3078](https://github.com/rollup/rollup/pull/3078): Add github actions workflow config for windows (@shellscape) +- [#3083](https://github.com/rollup/rollup/pull/3083): Properly reflect dependency file names in hash (@lukastaegert) +- [#3084](https://github.com/rollup/rollup/pull/3084): Fix "default" reexport issues in non ESM/System formats (@lukastaegert) + +## 1.20.2 + +_2019-08-25_ + +### Bug Fixes + +- Avoid an issue where circular namespace reexports would crash Rollup (#3074) + +### Pull Requests + +- [#3077](https://github.com/rollup/rollup/pull/3077): Handle namespaces that reexport themselves (@lukastaegert) + +## 1.20.1 + +_2019-08-22_ + +### Bug Fixes + +- Fix an issue where variable names inside dynamic import expressions were not rendered correctly (#3073) +- Fix type definition to allow a single watcher config as well as an array (#3074) + +### Pull Requests + +- [#3073](https://github.com/rollup/rollup/pull/3073): Fix wrong variable name in import expression (@lukastaegert) +- [#3074](https://github.com/rollup/rollup/pull/3074): Fixes type definition on watch and Watcher constructor (@MicahZoltu) + +## 1.20.0 + +_2019-08-21_ + +### Features + +- Add augmentChunkHash plugin hook to be able to reflect changes in renderChunk in the chunk hash (#2921) + +### Bug Fixes + +- Do not mutate the acorn options object (#3051) +- Make sure the order of emitted chunks always reflects the order in which they were emitted (#3055) +- Do not hang when there are strings containing comment-like syntax in some scenarios (#3069) + +### Pull Requests + +- [#2921](https://github.com/rollup/rollup/pull/2921): Add augmentChunkHash plugin hook (@isidrok) +- [#2995](https://github.com/rollup/rollup/pull/2995): Add info on installing locally to docs (@mesqueeb) +- [#3037](https://github.com/rollup/rollup/pull/3037): Refresh pull request labels (@shellscape) +- [#3048](https://github.com/rollup/rollup/pull/3048): Document ROLLUP_WATCH environment variable (@shellscape) +- [#3051](https://github.com/rollup/rollup/pull/3051): Avoid changes to the original options (.acorn) object (@LongTengDao) +- [#3052](https://github.com/rollup/rollup/pull/3052): Minor refactoring: Remove one try-catch (@KSXGitHub) +- [#3053](https://github.com/rollup/rollup/pull/3053): Refactor to use async-await in more places (@KSXGitHub) +- [#3055](https://github.com/rollup/rollup/pull/3055): Provide consistent chunking via a consistent order of entry modules when emitting chunks (@lukastaegert) +- [#3058](https://github.com/rollup/rollup/pull/3058): Remove acorn-bigint and acorn-dynamic-import from bundle (@LongTengDao) +- [#3061](https://github.com/rollup/rollup/pull/3061): Update to acorn@7 (@lukastaegert) +- [#3063](https://github.com/rollup/rollup/pull/3063): Auto-generate license file (@lukastaegert) +- [#3069](https://github.com/rollup/rollup/pull/3069): Prevent infinite loop when scanning for line-breaks and there are comment-like strings (@lukastaegert) + +## 1.19.4 + +_2019-08-07_ + +### Bug Fixes + +- Prevent invalid code when exporting an external namespace (#3034) +- Prevent invalid or non-equivalent code when simplifying expressions in return and throw statements (#3035) + +### Pull Requests + +- [#3034](https://github.com/rollup/rollup/pull/3034): Avoid generating .\* as export (@LongTengDao) +- [#3035](https://github.com/rollup/rollup/pull/3035): Prevent ASI errors for conditional expressions (@lukastaegert) +- [#3036](https://github.com/rollup/rollup/pull/3036): Fix documents to use https, not http (@giraffate) + +## 1.19.3 + +_2019-08-06_ + +### Bug Fixes + +- Fix wrong URLs in error messages (#3033) + +### Pull Requests + +- [#3033](https://github.com/rollup/rollup/pull/3033): Fix wrong URLs in error messages (@giraffate) + +## 1.19.2 + +_2019-08-05_ + +### Bug Fixes + +- Add bin file to package + +## 1.19.1 + +_2019-08-05_ + +### Bug Fixes + +- Remove wrong extension in package.json file (#3031) + +### Pull Requests + +- [#3031](https://github.com/rollup/rollup/pull/3031): Fix wrong extension (@lukastaegert) + +## 1.19.0 + +_2019-08-05_ + +### Features + +- Implement a new unified file emission API for assets and chunks with support for explicit file names (#2999) +- Use the id of the last module in a chunk as base for the chunk name if no better name is available (#3025) +- Use the id of the last module in a chunk as base for the variable name of a chunk in some formats if no better name is available (#2999) + +### Bug Fixes + +- Do not produce invalid variable names if an empty name is chosen for a virtual module (#3026) +- Fix an issue where a module variable name would conflict with a local variable name in some formats (#3020) + +### Pull Requests + +- [#2999](https://github.com/rollup/rollup/pull/2999): Unified file emission api (@lukastaegert) +- [#3020](https://github.com/rollup/rollup/pull/3020): Switch to a code-splitting build and update dependencies (@lukastaegert) +- [#3025](https://github.com/rollup/rollup/pull/3025): Use id of last module in chunk as name base for auto-generated chunks (@lukastaegert) +- [#3026](https://github.com/rollup/rollup/pull/3026): Avoid variable from empty module name be empty (@LongTengDao) + +## 1.18.0 + +_2019-08-01_ + +### Features + +- Add `externalLiveBindings: false` option to optimize code when live bindings are not needed (#3010) + +### Pull Requests + +- [#2997](https://github.com/rollup/rollup/pull/2997): Integrate coverage into CI setup (@lukastaegert) +- [#2998](https://github.com/rollup/rollup/pull/2998): Update readme badges (@lukastaegert) +- [#3010](https://github.com/rollup/rollup/pull/3010): Add option to prevent code for external live bindings (@lukastaegert) + +## 1.17.0 + +_2019-07-15_ + +### Features + +- Allow plugins to access current combined sourcemap in transform hook for coverage instrumentation (#2993) + +### Pull Requests + +- [#2987](https://github.com/rollup/rollup/pull/2987): Fix code fences for link (@johanholmerin) +- [#2989](https://github.com/rollup/rollup/pull/2989): Bump lodash from 4.17.11 to 4.17.14 (@dependabot) +- [#2993](https://github.com/rollup/rollup/pull/2993): Add getCombinedSourceMap in transform plugin context (@billowz) + +## 1.16.7 + +_2019-07-09_ + +### Bug Fixes + +- Fix an issue where exported import.meta properties would lead to invalid code (#2986) + +### Pull Requests + +- [#2985](https://github.com/rollup/rollup/pull/2985): Improve sourcemap types (@jridgewell) +- [#2986](https://github.com/rollup/rollup/pull/2986): Only overwrite content when resolving import.meta properties (@lukastaegert) + +## 1.16.6 + +_2019-07-04_ + +### Bug Fixes + +- Do not pass undefined to resolveDynamicImport for unresolvable template literals (#2984) + +### Pull Requests + +- [#2984](https://github.com/rollup/rollup/pull/2984): Always forward AST nodes for unresolvable dynamic imports (@lukastaegert) + +## 1.16.5 + +_2019-07-04_ + +### Bug Fixes + +- onwarn should still be called when --silent is used (#2982) +- Properly clean up watchers for files that are deleted between builds (#2982) + +### Pull Requests + +- [#2981](https://github.com/rollup/rollup/pull/2981): Do not skip onwarn handler when --silent is used (@lukastaegert) +- [#2982](https://github.com/rollup/rollup/pull/2982): Make tests run on Node 12, fix watcher cleanup issue (@lukastaegert) + +## 1.16.4 + +_2019-07-02_ + +### Bug Fixes + +- Do not show a TypeScript error when providing a location as number to this.warn and this.error (#2974) +- Use the correct TypeScript type for Sourcemap.version (#2976) + +### Pull Requests + +- [#2965](https://github.com/rollup/rollup/pull/2965): Use async readFile in getRollupDefaultPlugin (@kaksmet) +- [#2974](https://github.com/rollup/rollup/pull/2974): Align TS types, docs and implementation for this.warn and this.error (@lukastaegert) +- [#2976](https://github.com/rollup/rollup/pull/2976): Fix sourcemap type and update dependencies (@lukastaegert) + +## 1.16.3 + +_2019-06-29_ + +### Bug Fixes + +- Prevent name conflicts with unused function parameters (#2972) + +### Pull Requests + +- [#2972](https://github.com/rollup/rollup/pull/2972): Deconflict unused parameters (@lukastaegert) + +## 1.16.2 + +_2019-06-22_ + +### Bug Fixes + +- Properly wrap dynamic imports in Promises that can be caught when generating CJS output (#2958) + +### Pull Requests + +- [#2958](https://github.com/rollup/rollup/pull/2958): Make sure errors from dynamic imports can be caught (@lukastaegert) + +## 1.16.1 + +_2019-06-21_ + +### Pull Requests + +- [#2956](https://github.com/rollup/rollup/pull/2956): Add missing CLI docs for strictDeprecations (@lukastaegert) + +## 1.16.0 + +_2019-06-21_ + +### Features + +- Add strictDeprecations option to throw when currently or upcoming deprecated features are used (#2945) +- Keep annotations and comments when simplifying logical and conditional expressions (#2955) + +### Bug Fixes + +- Generate proper namespace objects when dynamically importing external dependencies for AMD or CJS formats (#2954) +- Fix dynamically imported variables not being resolved correctly when importing from an entry chunk with only a default export (#2954) +- Do not reexport default when reexporting a namespace (#2954) + +### Pull Requests + +- [#2945](https://github.com/rollup/rollup/pull/2945): Add option to handle use of features marked for deprecation as errors (@lukastaegert) +- [#2954](https://github.com/rollup/rollup/pull/2954): Improve dynamic import interop (@lukastaegert) +- [#2955](https://github.com/rollup/rollup/pull/2955): Keep annotations and comments when simplifying logical and conditional expressions (@lukastaegert) + +## 1.15.6 + +_2019-06-16_ + +### Bug Fixes + +- No longer use an alternate screen in watch mode to allow scrolling (#2942) +- Prioritize non-external imports over external ones when resolving conflicting namespace re-exports (#2893) + +### Pull Requests + +- [#2893](https://github.com/rollup/rollup/pull/2893): Improve handling of conflicting namespace exports (@aleclarson) +- [#2942](https://github.com/rollup/rollup/pull/2942): Get rid of alternate screen and simplify screen clearing (@lukastaegert) + +## 1.15.5 + +_2019-06-14_ + +### Bug Fixes + +- Do not include any comments for completely tree-shaken files so that `renderedLength === 0` is a reliable check (#2940) +- Do not cause type errors when returning `null` from `resolveId` (#2941) + +### Pull Requests + +- [#2940](https://github.com/rollup/rollup/pull/2940): Completely omit files that do not have any included statements (@lukastaegert) +- [#2941](https://github.com/rollup/rollup/pull/2941): Explicitly allow null as return value for various hooks (@lukastaegert) + +## 1.15.4 + +_2019-06-14_ + +### Bug Fixes + +- Improve how asset and chunk URLs are resolved for UMD, IIFE and CJS output (#2937) + +### Pull Requests + +- [#2937](https://github.com/rollup/rollup/pull/2937): Fix URL resolution to work when the current script contains query parameters (@lukastaegert) + +## 1.15.3 + +_2019-06-13_ + +### Bug Fixes + +- Always reemit assets and chunks from cached transform hooks (#2936) + +### Pull Requests + +- [#2936](https://github.com/rollup/rollup/pull/2936): Fix repeated re-emission of files emitted from a transform hook (@lukastaegert) + +## 1.15.2 + +_2019-06-13_ + +### Bug Fixes + +- Make sure chunks emitted from transform hooks are also emitted for incremental builds in watch mode (#2933) + +### Pull Requests + +- [#2933](https://github.com/rollup/rollup/pull/2933): Reemit chunks emitted from transform hooks (@lukastaegert) + +## 1.15.1 + +_2019-06-11_ + +### Bug Fixes + +- Do not fail when reexporting variables in dynamic entry points from other chunks (#2928) + +### Pull Requests + +- [#2928](https://github.com/rollup/rollup/pull/2928): Handle reexports from dynamic entries across chunk (@lukastaegert) + +## 1.15.0 + +_2019-06-11_ + +### Features + +- Tone down try-catch deoptimization while maintaining polyfill support (#2918) + +### Bug Fixes + +- Handle feature detection with "typeof" for regular expressios (#2916) +- Deoptimize `'' + variable'` type coercion as expression statement for feature detection (#2917) +- Always observe argument side-effects when tree-shaking (#2924) + +### Pull Requests + +- [#2916](https://github.com/rollup/rollup/pull/2916): Deoptimize typeof for regular expression literals to better support es6-shim (@lukastaegert) +- [#2917](https://github.com/rollup/rollup/pull/2917): Support implicit type coercion errors in es5-shim (@lukastaegert) +- [#2918](https://github.com/rollup/rollup/pull/2918): Deoptimize try-catch less radically (@lukastaegert) +- [#2924](https://github.com/rollup/rollup/pull/2924): Do not tree-shake arguments with side-effects (@lukastaegert) + +## 1.14.6 + +_2019-06-10_ + +### Bug Fixes + +- Fix an issue where call arguments were not included in try statements (#2914) + +### Pull Requests + +- [#2914](https://github.com/rollup/rollup/pull/2914): Properly include try statements for each pass when deoptimization is deactivated (@lukastaegert) + +## 1.14.5 + +_2019-06-09_ + +### Bug Fixes + +- Keep external ids unmodified when using the object form of resolveId (#2907) +- Cache dynamic import resolutions when using Rollup cache (#2908) +- Keep all necessary parentheses when tree-shaking call arguments (#2911) + +### Pull Requests + +- [#2906](https://github.com/rollup/rollup/pull/2906): Update dependencies (@lukastaegert) +- [#2907](https://github.com/rollup/rollup/pull/2907): Do not renormalize external ids when using the object form (@lukastaegert) +- [#2908](https://github.com/rollup/rollup/pull/2908): Cache dynamic ids if possible (@lukastaegert) +- [#2911](https://github.com/rollup/rollup/pull/2911): Fix treeshaken parameters around parentheses (@manucorporat) + +## 1.14.4 + +_2019-06-07_ + +### Bug Fixes + +- Do not omit external re-exports for `moduleSideEffects: false` (#2905) + +### Pull Requests + +- [#2905](https://github.com/rollup/rollup/pull/2905): Make sure external re-exports are included for moduleSideEffects: false (@lukastaegert) + +## 1.14.3 + +_2019-06-06_ + +### Bug Fixes + +- Generate correct external imports when importing from a directory that would be above the root of the current working directory (#2902) + +### Pull Requests + +- [#2902](https://github.com/rollup/rollup/pull/2902): Use browser relative path algorithm for chunks (@lukastaegert) + +## 1.14.2 + +_2019-06-05_ + +### Bug Fixes + +- Prevent unnecessary inclusion of external namespace import in certain situations (#2900) + +### Pull Requests + +- [#2900](https://github.com/rollup/rollup/pull/2900): Handle early bind for member expressions (@lukastaegert) + +## 1.14.1 + +_2019-06-05_ + +### Bug Fixes + +- Fix an issue where try-statements were not included properly when a variable declared inside the statement was accessed outside it (#2898) +- Fix an issue where `await` expressions were not included properly (#2899) + +### Pull Requests + +- [#2898](https://github.com/rollup/rollup/pull/2898): Properly include try-catch-statements even if they have already been included in some way (@lukastaegert) +- [#2899](https://github.com/rollup/rollup/pull/2899): Fix unintended early return in await inclusion handling (@lukastaegert) + +## 1.14.0 + +_2019-06-05_ + +### Features + +- Deoptimize code inside and called from try-statements for feature detection (#2892) +- Tree-shake unused call arguments (#2892) + +### Pull Requests + +- [#2892](https://github.com/rollup/rollup/pull/2892): Implement try-statement-deoptimization for feature detection, tree-shake unused arguments (@lukastaegert) + +## 1.13.1 + +_2019-06-01_ + +### Bug Fixes + +- Avoid conflicts between top-level module, require etc. and CommonJS runtimes (#2889) + +### Pull Requests + +- [#2888](https://github.com/rollup/rollup/pull/2888): Enable full TypeScript strict mode (@lukastaegert) +- [#2889](https://github.com/rollup/rollup/pull/2889): Protect all module globals for CJS output from being redefined (@lukastaegert) + +## 1.13.0 + +_2019-05-31_ + +### Features + +- Omit `exports` and `module` from SystemJS wrapper if possible (#2880) +- Try to use the first letters of names when mangling exports (#2885) + +### Bug Fixes + +- Avoid conflicts with local variables when using format specific globals to render dynamic imports and file URLs (#2880) +- Do not produce undefined reexports when reexporting from entry points (#2885) + +### Pull Requests + +- [#2880](https://github.com/rollup/rollup/pull/2880): Deconflict global variables used inside format-specific code (@lukastaegert) +- [#2885](https://github.com/rollup/rollup/pull/2885): Do not produce undefined reexports when reexporting from entry points and refactor chunk linking (@lukastaegert) + +## 1.12.5 + +_2019-05-30_ + +### Pull Requests + +- [#2884](https://github.com/rollup/rollup/pull/2884): Update pluginutils for new micormatch and reduced bundle size (@lukastaegert) + +## 1.12.4 + +_2019-05-27_ + +### Bug Fixes + +- Show correct error stack trace for errors throw in "load" hooks (#2871) + +### Pull Requests + +- [#2875](https://github.com/rollup/rollup/pull/2875): Mention subfolders in docs (@lukastaegert) +- [#2871](https://github.com/rollup/rollup/pull/2871): Reserve error stack information (@LongTengDao) + +## 1.12.3 + +_2019-05-19_ + +### Bug Fixes + +- Prevent duplicate imports when exports are reexported as default exports (#2866) + +### Pull Requests + +- [#2755](https://github.com/rollup/rollup/pull/2755): Enable TypeScript strictNullChecks (@edsrzf) +- [#2866](https://github.com/rollup/rollup/pull/2866): Properly deduplicate reexported default exports (@lukastaegert) + +## 1.12.2 + +_2019-05-17_ + +### Bug Fixes + +- Do not fail when using clearScreen:false in watchMode (#2858) +- Properly resolve star reexports when preserving modules (#2860) + +### Pull Requests + +- [#2858](https://github.com/rollup/rollup/pull/2858): Declare processConfigsErr before use (@humphd) +- [#2860](https://github.com/rollup/rollup/pull/2860): Keep nested exports with preserveModules (@TomCaserta) +- [#2864](https://github.com/rollup/rollup/pull/2864): Cache transitive reexport detection (@lukastaegert) + +## 1.12.1 + +_2019-05-16_ + +### Bug Fixes + +- Extend file name sanitation to also replace "?" and "\*" e.g. when preserving modules with the updated commonjs plugin (#2860) +- Do not ignore module transformer that return an empty string (#2861) + +### Pull Requests + +- [#2860](https://github.com/rollup/rollup/pull/2860): Update to latest plugins and extend file name sanitation (@lukastaegert) +- [#2861](https://github.com/rollup/rollup/pull/2861): Allow transformers to return an empty string (@lukastaegert) + +## 1.12.0 + +_2019-05-15_ + +### Features + +- Add `treeshake.moduleSideEffects` option to allow removing empty imports without a side-effect check (#2844) +- Extend plugin API to allow marking modules as side-effect-free (#2844) +- Extend `this.resolve` plugin context function with an option to skip the `resolveId` hook of the calling plugin (#2844) +- Add `isEntry` flag to `this.getModuleInfo` plugin context function (#2844) +- Distribute Rollup as optimized ES2015 code (#2851) + +### Pull Requests + +- [#2844](https://github.com/rollup/rollup/pull/2844): Add options and hooks to control module side effects (@lukastaegert) +- [#2851](https://github.com/rollup/rollup/pull/2851): Switch to ES2015 output (@lukastaegert) + +## 1.11.3 + +_2019-05-05_ + +### Bug Fixes + +- Quote es3 keywords in namespace objects (#2825) + +### Pull Requests + +- [#2825](https://github.com/rollup/rollup/pull/2825): Add es3 support for namespace object import (@sormy) + +## 1.11.2 + +_2019-05-04_ + +### Bug Fixes + +- Prevent a crash when handling circular namespace exports (#2836) + +### Pull Requests + +- [#2836](https://github.com/rollup/rollup/pull/2836): Make sure circular `export * from X` does not stack overflow (@Swatinem) + +## 1.11.1 + +_2019-05-04_ + +### Bug Fixes + +- Fix an issue where rendered exports were reported as "removed" in the bundle information (#2835) + +### Pull Requests + +- [#2835](https://github.com/rollup/rollup/pull/2835): Fix `removedExports` to correctly track the exported item (@Swatinem) + +## 1.11.0 + +_2019-05-03_ + +### Features + +- Add `emitChunk` plugin context function to emit additional entry chunks that can be referenced from the code (#2809) +- Allow `manualChunks` to be a function (#2831) +- Omit `.js` extensions in AMD imports to make sure an AMD `baseUrl` would work (#2809) +- Automatically use the name of the imported module as a base for dynamically imported chunks (#2809) +- Add `resolveFileUrl` plugin hook to replace `resolveAssetUrl` and handle emitted chunks as well (#2809) +- Add `resolve` plugin hook to replace `resolveId` and `isExternal` that returns an object (#2829) +- Allow `resolveDynamicImport` to return an `{id, external}` object to also resolve unresolvable dynamic imports to a module (#2829) + +### Bug Fixes + +- Do not create invalid code if a dynamic import contains nothing but reexports (#2809) +- Do not fail if modules that define a manual chunk depend on each other (#2809) +- Do not fail if a module that defines a manual chunk is the dependency of a module defining a different manual chunk (#2809) +- No longer fail for unnamed duplicate entry points but combine them (#2809) +- Always return `string | null` from `this.resolveId` even if some `resolveId` hooks return objects (#2829) +- Show proper warnings when `resolveDynamicImport` resolves to a non-external module that does not exist (#2829) + +### Pull Requests + +- [#2809](https://github.com/rollup/rollup/pull/2809): Add hook for dynamic entry chunk emission (@lukastaegert) +- [#2821](https://github.com/rollup/rollup/pull/2821): Fix syntax error in documentation (@FFxSquall) +- [#2829](https://github.com/rollup/rollup/pull/2829): Improve id resolution (@lukastaegert) +- [#2831](https://github.com/rollup/rollup/pull/2831): Allow manualChunks to be a function (@lukastaegert) +- [#2832](https://github.com/rollup/rollup/pull/2832): Improve `generateBundle` documentation (@lukastaegert) +- [#2833](https://github.com/rollup/rollup/pull/2833): Update dependencies (@lukastaegert) + +## 1.10.1 + +_2019-04-19_ + +### Bug Fixes + +- Invalid options.format values will now trigger a helpful error (#2813) + +### Pull Requests + +- [#2812](https://github.com/rollup/rollup/pull/2812): Minor documentation update (@dnalborczyk) +- [#2813](https://github.com/rollup/rollup/pull/2813): Catch invalid options.format values (@marijnh) +- [#2816](https://github.com/rollup/rollup/pull/2816): Update all dependencies to fix security issues (@lukastaegert) + +## 1.10.0 + +_2019-04-11_ + +### Features + +- Improve generated code to polyfill `import.meta.url` (#2785) +- Add plugin hook to configure handling of `import.meta` (#2785) +- Improve generated code when accessing URLs of emitted assets (#2796) +- Add plugin hook to configure the generated code when accessing URLs of emitted assets (#2796) + +### Bug Fixes + +- No longer resolve assets to their parent URL in some cases (#2796) + +### Pull Requests + +- [#2785](https://github.com/rollup/rollup/pull/2785): Refactor handling of import.meta.url and add option to configure behaviour (@lukastaegert) +- [#2796](https://github.com/rollup/rollup/pull/2796): Improve and fix asset emission (@lukastaegert) + +## 1.9.3 + +_2019-04-10_ + +### Bug Fixes + +- Simplify return expressions that are evaluated before the surrounding function is bound (#2803) + +### Pull Requests + +- [#2803](https://github.com/rollup/rollup/pull/2803): Handle out-of-order binding of identifiers to improve tree-shaking (@lukastaegert) + +## 1.9.2 + +_2019-04-10_ + +### Bug Fixes + +- Allowing replacing `output.file` with `output.dir` in the `outputOptions` hook (#2802) + +### Pull Requests + +- [#2802](https://github.com/rollup/rollup/pull/2802): Observe modified output options in bundle.write (@lukastaegert) + +## 1.9.1 + +_2019-04-10_ + +### Bug Fixes + +- Make sure inline comments in dynamic imports are preserved (#2797) + +### Pull Requests + +- [#2797](https://github.com/rollup/rollup/pull/2797): Emit inline comments inside dynamic import (@manucorporat) + +## 1.9.0 + +_2019-04-05_ + +### Features + +- Add built-in support for bigint (#2789) + +### Pull Requests + +- [#2789](https://github.com/rollup/rollup/pull/2789): Ship with bigint support built-in (@danielgindi) +- [#2791](https://github.com/rollup/rollup/pull/2791): Use shared extractAssignedNames from rollup-pluginutils (@lukastaegert) +- [#2792](https://github.com/rollup/rollup/pull/2792): Test that rollup-plugin-commonjs works with preserveModules (@lukastaegert) + +## 1.8.0 + +_2019-04-02_ + +### Features + +- Support `module` as alias for `esm` and `commonjs` for `cjs` to match Node (#2783) + +### Pull Requests + +- [#2782](https://github.com/rollup/rollup/pull/2782): Inline interopDefault in config loading (@guybedford) +- [#2783](https://github.com/rollup/rollup/pull/2783): Support Node-style format aliases (@guybedford) + +## 1.7.4 + +_2019-03-28_ + +### Bug Fixes + +- Improve TypeScript type of the treeshaking options (#2779) + +### Pull Requests + +- [#2779](https://github.com/rollup/rollup/pull/2779): Make all properties in TreeshakingOptions optional (@ndelangen) + +## 1.7.3 + +_2019-03-24_ + +### Bug Fixes + +- Use getters when re-exporting live-bindings (#2765) + +### Pull Requests + +- [#2765](https://github.com/rollup/rollup/pull/2765): Support exporting live-bindings from other chunks or external dependencies (@lukastaegert) + +## 1.7.2 + +_2019-03-24_ + +### Bug Fixes + +- Make sure relative external ids are resolved correctly (#2774) + +### Pull Requests + +- [#2774](https://github.com/rollup/rollup/pull/2774): Resolve relative external ids (@lukastaegert) + +## 1.7.1 + +_2019-03-24_ + +### Bug Fixes + +- Prevent invalid code when exporting several hundred identifiers from a chunk (#2768) +- Do not wrongly deconflict labels (#2776) + +### Pull Requests + +- [#2768](https://github.com/rollup/rollup/pull/2768): Sanitize shortened internal export names (@lukastaegert) +- [#2769](https://github.com/rollup/rollup/pull/2769): Update dependencies and fix security issue (@lukastaegert) +- [#2776](https://github.com/rollup/rollup/pull/2776): Do not treat break labels as identifiers (@lukastaegert) + +## 1.7.0 + +_2019-03-20_ + +### Features + +- Sort chunk exports by name for greater consistency (#2757) + +### Bug Fixes + +- Fix a situation where tree-shakeable code would not be removed in an indeterminate manner (#2757) + +### Pull Requests + +- [#2757](https://github.com/rollup/rollup/pull/2757): Sort modules before binding, sort exports (@lukastaegert) + +## 1.6.1 + +_2019-03-20_ + +### Bug Fixes + +- Avoid name clashes of unused default exports when tree-shaking is false (#2758) +- Do not crash when generating SystemJS bundles containing array patterns with member expressions (#2760) + +### Pull Requests + +- [#2758](https://github.com/rollup/rollup/pull/2758): Make sure unused default exports are deconflicted when tree-shaking is false (@lukastaegert) +- [#2760](https://github.com/rollup/rollup/pull/2760): Handle member expressions in array patterns (@lukastaegert) + +## 1.6.0 + +_2019-03-08_ + +### Features + +- Add plugin hook to modify output options (#2736) + +### Pull Requests + +- [#2736](https://github.com/rollup/rollup/pull/2736): Add hook for modifying OutputOptions (@Comandeer) + +## 1.5.0 + +_2019-03-07_ + +### Features + +- Allow resolving to a different id while marking it as external at the same time (#2734) + +### Pull Requests + +- [#2734](https://github.com/rollup/rollup/pull/2734): Allow resolveId to return an object (@lukastaegert) + +## 1.4.2 + +_2019-03-07_ + +### Bug Fixes + +- Respect variable identity of exports when hashing (#2741) +- Resolve a situations where a variable was imported twice with the same name (#2737) + +### Pull Requests + +- [#2741](https://github.com/rollup/rollup/pull/2741): Fix hashing when different variable are exported using the same name (@lukastaegert) +- [#2737](https://github.com/rollup/rollup/pull/2737): Fix duplicate imports with conflicting names (@lukastaegert) + +## 1.4.1 + +_2019-03-04_ + +### Bug Fixes + +- Do not treat the import target "" as external by default (#2733) + +### Pull Requests + +- [#2733](https://github.com/rollup/rollup/pull/2733): Do not treat the import target "" as external by default (@LongTengDao) + +## 1.4.0 + +_2019-03-01_ + +### Features + +- Add option to change the name of the dynamic import function to allow polyfilling it (#2723) + +### Pull Requests + +- [#2723](https://github.com/rollup/rollup/pull/2723): Add dynamicImportFunction option (@keithamus) + +## 1.3.3 + +_2019-03-01_ + +### Bug Fixes + +- Fix performance regression when handling long chains of calls to property methods (#2732) + +### Pull Requests + +- [#2730](https://github.com/rollup/rollup/pull/2730): Order types, interfaces, classes, and object members (@lukastaegert) +- [#2732](https://github.com/rollup/rollup/pull/2732): Take chunk export mode into account when reexporting default (@lukastaegert) + +## 1.3.2 + +_2019-02-27_ + +### Bug Fixes + +- Allow ids of default exported classes to be exported separately (#2728) + +### Pull Requests + +- [#2728](https://github.com/rollup/rollup/pull/2728): Update dependencies (@lukastaegert) + +## 1.3.1 + +_2019-02-27_ + +### Bug Fixes + +- Correctly reexport the default export from entry chunks (#2727) + +### Pull Requests + +- [#2727](https://github.com/rollup/rollup/pull/2727): Take chunk export mode into account when reexporting default (@lukastaegert) + +## 1.3.0 + +_2019-02-26_ + +### Features + +- Treeshake call expressions prefixed with UglifyJS style `@__PURE__` annotations (#2429) + +### Pull Requests + +- [#2429](https://github.com/rollup/rollup/pull/2429): Add support for /_#**PURE**_/ comments (@conartist6 and @lukastaegert) + +## 1.2.5 + +_2019-02-26_ + +### Bug Fixes + +- Store external ids reported by plugins in watch mode (#2718) + +### Pull Requests + +- [#2718](https://github.com/rollup/rollup/pull/2718): Incremental external (@andreas-karlsson) + +## 1.2.4 + +_2019-02-26_ + +### Bug Fixes + +- Fix an issue where a variable was imported twice under the same name (#2715) + +### Pull Requests + +- [#2715](https://github.com/rollup/rollup/pull/2715): Deduplicate imports referencing default exports and their original variables (@lukastaegert) + +## 1.2.3 + +_2019-02-23_ + +### Bug Fixes + +- Use correct path when rendering dynamic imports where the entry module is empty (#2714) + +### Pull Requests + +- [#2714](https://github.com/rollup/rollup/pull/2714): Properly render dynamic imports when imported module is empty (@lukastaegert) + +## 1.2.2 + +_2019-02-19_ + +### Bug Fixes + +- Fix wrong external imports when using the `paths` options only for some outputs (#2706) + +### Pull Requests + +- [#2706](https://github.com/rollup/rollup/pull/2706): Always recreate paths for external modules (@lukastaegert) + +## 1.2.1 + +_2019-02-17_ + +### Bug Fixes + +- Fix ESM version of Rollup (#2705) + +### Pull Requests + +- [#2705](https://github.com/rollup/rollup/pull/2705): Fix ESM version of Rollup (@lukastaegert) + +## 1.2.0 + +_2019-02-17_ + +### Features + +- Fewer renamed variables due to a completely reimplemented deconflicting logic (#2689) + +### Bug Fixes + +- Respect rendered and tree-shaken exports when determining chunk hashes (#2695) +- Fix an error when dynamic imports end up in the same chunk as one of their importees (#2677) +- Do not generate invalid code when expressions containing IIFEs are simplified (#2696) +- Do not throw an error when more than ten bundles are watched (#2700) +- Treat re-exported globals in a spec-compliant way (#2691) +- Fix issues related to wrongly renamed variables (#2689) +- Do not throw an error if config files contain non-default exports (#2673) +- Improve type of `RollupOutput.output` to guarantee at least one chunk (#2679) + +### Pull Requests + +- [#2673](https://github.com/rollup/rollup/pull/2673): Allow config files to have non-default exports (@swansontec) +- [#2677](https://github.com/rollup/rollup/pull/2677): Prevent final resolution and facade creation for inlined dynamic imports (@Rich-Harris and @lukastaegert) +- [#2679](https://github.com/rollup/rollup/pull/2679): Improve type of `RollupOutput.output` (@MattiasBuelens) +- [#2689](https://github.com/rollup/rollup/pull/2689): Reimplement variable deconflicting logic (@lukastaegert) +- [#2691](https://github.com/rollup/rollup/pull/2691): Fix CI issues and update acorn dependency (@lukastaegert) +- [#2693](https://github.com/rollup/rollup/pull/2693): Fix typo in export-globals test (@MattiasBuelens) +- [#2695](https://github.com/rollup/rollup/pull/2695): Respect rendered exports when generating chunk hashes (@lukastaegert) +- [#2696](https://github.com/rollup/rollup/pull/2696): Correctly render function expression inside simplified expression statements (@lukastaegert) +- [#2700](https://github.com/rollup/rollup/pull/2700): Add a fix for MaxListenersExceededWarning (@luwes) +- [#2703](https://github.com/rollup/rollup/pull/2703): Update rollup-pluginutils (@lukastaegert) + +## 1.1.2 + +_2019-01-21_ + +### Bug Fixes + +- Tree-shaken dynamic imports no longer leave behind `undefined` entries in the bundle information (#2663) +- Dynamic imports in dynamically imported files could lead to crashes and would not always create new chunks (#2664) + +### Pull Requests + +- [#2663](https://github.com/rollup/rollup/pull/2663): Do not include tree-shaken dynamic imports in bundle information (@lukastaegert) +- [#2664](https://github.com/rollup/rollup/pull/2664): Properly handle dynamic imports declared in dynamically imported files (@everdimension) + +## 1.1.1 + +_2019-01-19_ + +### Bug Fixes + +- Make sure object prototype methods are not considered to be falsy when tree-shaking (#2652) + +### Pull Requests + +- [#2652](https://github.com/rollup/rollup/pull/2652): Make sure object prototype methods are not considered to be falsy (@lukastaegert) +- [#2654](https://github.com/rollup/rollup/pull/2654): Use correct signature for `this.setAssetSource` in docs (@everdimension) +- [#2656](https://github.com/rollup/rollup/pull/2656): Swap descriptions for `[extname]` and `[ext]` in docs (@tivac) + +## 1.1.0 + +_2019-01-09_ + +### Features + +- Make `this.meta` available from the `options` plugin hook (#2642) +- Add a new `writeBundle` plugin hook that is called _after_ all files have been written (#2643) + +### Bug Fixes + +- Make sure the `acorn` import of the bundled non-ESM acorn plugins is correctly translated to ESM (#2636) +- Make sure input options are actually passed to the `buildStart` hook (#2642) + +### Pull Requests + +- [#2636](https://github.com/rollup/rollup/pull/2636): Improve how acorn is imported, update dependencies (@lukastaegert) +- [#2642](https://github.com/rollup/rollup/pull/2642): Make this.meta available in options hook, pass input options to buildStart (@lukastaegert) +- [#2643](https://github.com/rollup/rollup/pull/2643): Implement writeBundle hook (@lukastaegert) + +## 1.0.2 + +_2019-01-05_ + +### Bug Fixes + +- Make sure the transform hook is always reevaluated when a file watched by the hook changes (#2633) +- Fix a crash when generating hashes for tree-shaken dynamic imports (#2638) +- Fix a crash and some inconsistencies when using the acorn-bigint plugin (#2640) + +### Pull Requests + +- [#2633](https://github.com/rollup/rollup/pull/2633): Document `this.addWatchFile` and make sure it also declares transform dependencies (@lukastaegert) +- [#2635](https://github.com/rollup/rollup/pull/2635): Make sure `code` is optional in warning type (@lukastaegert) +- [#2638](https://github.com/rollup/rollup/pull/2638): Do not fail when generating hashes for tree-shaken dynamic imports (@lukastaegert) +- [#2640](https://github.com/rollup/rollup/pull/2640): Always treat bigints as unknown (@lukastaegert) +- [#2641](https://github.com/rollup/rollup/pull/2641): Make sure all CLI options are listed in the summary (@lukastaegert) + +## 1.0.1 + +_2019-01-03_ + +### Bug Fixes + +- Properly handle reexporting an external default export for non-ESM targets when using named exports mode (#2620) +- Do not (wrongly) re-declare input options in the merged `RollupOptions` type (#2622) + +### Pull Requests + +- [#2620](https://github.com/rollup/rollup/pull/2620): Fixed issue with reexporting default as default with `{exports: named, interop: true}` options (@Andarist) +- [#2622](https://github.com/rollup/rollup/pull/2622): Simplify RollupOptions (@Kinrany) +- [#2627](https://github.com/rollup/rollup/pull/2627): Show how to skip imports for optional plugins (@chris-morgan) + +## 1.0.0 + +_2018-12-28_ + +### Breaking Changes + +- Several (mostly deprecated) options have been removed or renamed (#2293, #2409): + - banner -> output.banner + - dest -> output.file + - entry -> input + - experimentalCodeSplitting -> now always active + - experimentalDynamicImport -> now always active + - experimentalPreserveModules -> preserveModules + - exports -> output.exports + - extend -> output.extend + - footer -> output.footer + - format -> output.format + - freeze -> output.freeze + - globals -> output.globals + - indent -> output.indent + - interop -> output.interop + - intro -> output.intro + - load -> use plugin API + - moduleName -> output.name + - name -> output.name + - noConflict -> output.noConflict + - output.moduleId -> output.amd.id + - outro -> output.outro + - paths -> output.paths + - preferConst -> output.preferConst + - pureExternalModules -> treeshake.pureExternalModules + - resolveExternal -> use plugin API + - resolveId -> use plugin API + - sourcemap -> output.sourcemap + - sourceMap -> output.sourcemap + - sourceMapFile -> output.sourcemapFile + - strict -> output.strict + - targets -> use output as an array + - transform -> use plugin API + - useStrict -> output.strict +- In general, output options can no longer be used as input options (#2409) +- `bundle.generate` and `bundle.write` now return a new format (#2293) +- Several plugin hooks have become deprecated and will display warnings when used (#2409): + - transformBundle + - transformChunk + - ongenerate + - onwrite +- Plugin transform dependencies are deprecated in favour of using the `this.addWatchFile` plugin context function (#2409) +- Accessing `this.watcher` in plugin hooks is deprecated in favour of the `watchChange` plugin hook and the `this.addWatchFile` plugin context function (#2409) +- Using dynamic import statements will by default create a new chunk unless `inlineDynamicImports` is used (#2293) +- Rollup now uses acorn@6 which means that acorn plugins must be compatible with this version; acorn is now external for non-browser builds to make plugins work (#2293) + +### Features + +- The `--dir` ClI option can now be aliased as `-d` (#2293) +- The `--input` option now supports named entry points via `=` (#2293) + +### Bug Fixes + +- Both the `--input` option as well as the default CLI option now support named inputs (#2293) + +### Pull Requests + +- [#2293](https://github.com/rollup/rollup/pull/2293): Unify code paths for 1.0 relase and update documentation (@guybedford and @lukastaegert) +- [#2409](https://github.com/rollup/rollup/pull/2409): Remove old deprecated features and add new deprecation warnings (@guybedford) +- [#2486](https://github.com/rollup/rollup/pull/2486): Upgrade to acorn 6 (@marijnh) +- [#2611](https://github.com/rollup/rollup/pull/2611): Fix hook's name in test description (@Andarist) +- [#2612](https://github.com/rollup/rollup/pull/2612): Fix a self-contradicting comment in the docs (@LongTengDao) + +## 0.68.2 + +_2018-12-23_ + +### Bug Fixes + +- Do not assume hoisted variables to have been initialized (#2607) + +### Pull Requests + +- [#2607](https://github.com/rollup/rollup/pull/2607): Fix an issues where hoisted variables were assumed to have been initialized (@lye) + +## 0.68.1 + +_2018-12-19_ + +### Bug Fixes + +- Fix an issue with UMD wrappers where a variable is used without being defined (#2600) + +### Pull Requests + +- [#2600](https://github.com/rollup/rollup/pull/2600): Fix UMD and IIFE wrapper issues and add comprehensive functional wrapper tests (@lukastaegert) + +## 0.68.0 + +_2018-12-16_ + +### Breaking Changes + +- `optimizeChunks` is renamed to `experimentalOptimizeChunks` to reflect this feature is not production-ready yet (#2575) + +### Features + +- Plugins can iterate all module ids via `this.moduleIds` (#2565) +- Plugins can get graph information about a module via `this.getModuleInfo(id)` (#2565) +- Plugins and JS API users get more information about the generated chunks: `dynamicImports`, `facadeModuleId`, `isDynamicEntry`, `name` (#2575) +- Tree-shaken dynamic imports will no longer create chunks or influence chunking in any way (#2575) +- Dynamic imports will no longer follow the `entryFileNames` but the `chunkFileNames` property reflecting those are solely internally used (#2575) +- If there are chunk naming conflicts, entry chunks will always take precedence (#2575) +- If an entry facade is created, only the facade chunk is marked as `isEntry` (#2575) +- Dynamic chunks will only be marked as `isEntry` if they are actually entry chunks as well; thus there is now a 1-to-1 correspondence between modules listed in `input` and chunks marked as `isEntry` (#2575) +- Chunks no longer contain imports for variables that are tree-shaken in the chunk but used in other chunks (#2584) +- Chunks will always import re-exported variables directly from the chunk where they are originally exported from (#2584) +- Null characters will be pruned from chunk ids to allow for virtually created chunks and make `rollup-plugin-multi-entry` compatible with code-splitting and thus the upcoming 1.0 version (#2590) +- Simplify the UMD wrapper code as much as possible, especially if there are no exports (#2594) +- The UMD wrapper will now work in strict mode by checking for `self` before `this` when determining the global variable (#2594) + +### Bug Fixes + +- If a facade is created for a dynamic entry point, this facade will be imported instead of the facaded chunk (#2575) +- Manual chunks that include multiple entry points will have proper facades created for all entry points if necessary (#2575) +- If missing exports are shimmed, the shim variable will not be global but created on a per-module basis and is deconflicted with variables having the same name (#2584) +- Missing export shims work properly in SystemJS (#2584) +- `preserveModules` now handles dynamic namespace imports (#2584) +- Fix chunk execution order in certain scenarios (#2584) +- Exports and assignments using destructuring syntax will properly update the exported variables when generating SystemJS output (#2587) +- Hashes in chunk names will now also take dynamic imports into account (#2596) + +### Pull Requests + +- [#2565](https://github.com/rollup/rollup/pull/2565): Provide module graph information on the plugin context (@samccone) +- [#2575](https://github.com/rollup/rollup/pull/2575): Extend bundle information, tree-shake dynamic imports, fix dynamic import facade creation, support manual chunks with multiple entry points, make `optimizeChunks` experimental (@lukastaegert) +- [#2577](https://github.com/rollup/rollup/pull/2577): Update dependencies (@lukastaegert) +- [#2584](https://github.com/rollup/rollup/pull/2584): Prune tree-shaken chunk imports, fix missing export shimming, support dynamic namespaces when preserving modules, improve chunk execution order (@lukastaegert) +- [#2587](https://github.com/rollup/rollup/pull/2587): Support exports using destructuring declarations and assignments in SystemJS (@lukastaegert) +- [#2590](https://github.com/rollup/rollup/pull/2590): Make sure chunk ids do not contain invalid characters to allow for chunks to correspond to virtual modules (@lukastaegert) +- [#2594](https://github.com/rollup/rollup/pull/2594): Simplify UMD wrapper code and make sure it works in strict mode (@lukastaegert) +- [#2596](https://github.com/rollup/rollup/pull/2596): Take both static and dynamic dependencies into account when calculating hashes (@lukastaegert) + +## 0.67.4 + +_2018-12-03_ + +### Bug Fixes + +- Prevent corrupt source maps for files with very long lines (#2571) + +### Pull Requests + +- [#2571](https://github.com/rollup/rollup/pull/2571): Fix an issue with long lines in sourcemaps (@mislav) + +## 0.67.3 + +_2018-11-17_ + +### Bug Fixes + +- Make sure the ESM browser build is actually published to npm (#2560) +- Throw proper error when using `inlineDynamicImports` with `experimentalPreserveModules` (#2560) + +### Pull Requests + +- [#2552](https://github.com/rollup/rollup/pull/2552): Properly include ESM browser build in package (@lukastaegert) +- [#2560](https://github.com/rollup/rollup/pull/2560): Show proper error when using `inlineDynamicImports` with `experimentalPreserveModules` (@clarkdo) + +## 0.67.2 + +_2018-11-17_ + +### Bug Fixes + +- Prevent crash when not returning sourcemaps from `renderChunk` plugin hook (#2558) + +### Pull Requests + +- [#2558](https://github.com/rollup/rollup/pull/2558): Prevent crash when not returning sourcemaps from `renderChunk` (@kyle1320) + +## 0.67.1 + +_2018-11-11_ + +### Bug Fixes + +- Deconflict CLI entry points with same name but on different paths if no explicit naming is used (#2548) + +### Pull Requests + +- [#2548](https://github.com/rollup/rollup/pull/2548): Deconflict CLI entry points with same name but on different paths if no explicit naming is used (@lukastaegert) + +## 0.67.0 + +_2018-11-04_ + +### Breaking Changes + +none + +### Features + +- Do not resolve external dynamic imports via plugins to match the logic for static external imports again (#2505) +- Support virtual modules created by plugins when preserving modules (#2511) +- Add new `output.sourcemapExcludeSources` option to exclude the actual sources from sourcemaps (#2531) + +### Bug Fixes + +- Fix TypeScript type for sourcemaps (#2507) +- Fix order of external and inter-chunk imports to match the proper execution order (#2508) +- Do not tree-shake children of unknown nodes to e.g. properly handle do-expressions via acorn plugin (#2510) +- Prevent memory leak when using the bundle as cache (#2522) +- Fix mis-placed semicolons for certain SystemJS exports (#2529) + +### Pull Requests + +- [#2505](https://github.com/rollup/rollup/pull/2505): Do not resolve external dynamic imports via plugins (@lukastaegert) +- [#2507](https://github.com/rollup/rollup/pull/2507): Fix public sourcemap type (@aMarCruz) +- [#2508](https://github.com/rollup/rollup/pull/2508): Improve execution order of chunks and externals (@lukastaegert) +- [#2510](https://github.com/rollup/rollup/pull/2510): Do not tree-shake children of unknown nodes to e.g. properly handle do-expressions via acorn plugin (@devsnek) +- [#2511](https://github.com/rollup/rollup/pull/2511): Create chunks for virtual modules when preserving modules (@lukastaegert) +- [#2522](https://github.com/rollup/rollup/pull/2522): Prevent memory leak when using the bundle as cache (@kyle1320) +- [#2529](https://github.com/rollup/rollup/pull/2529): Fix mis-placed semicolons for certain SystemJS exports (@kyle1320) +- [#2531](https://github.com/rollup/rollup/pull/2531): add `sourcemapExcludeSources` option to exclude the source content from sourcemaps (@kitsonk) + +## 0.66.6 + +_2018-10-10_ + +- Properly deconflict function and class declaration ids of reassigned default exports ([#2502](https://github.com/rollup/rollup/pull/2502)) + +## 0.66.5 + +_2018-10-09_ + +- Remove cache from memory once no longer needed ([#2496](https://github.com/rollup/rollup/pull/2496)) +- Provide better error message when reexporting external namespace reexports ([#2499](https://github.com/rollup/rollup/pull/2499)) + +## 0.66.4 + +_2018-10-04_ + +- Fix links in warnings and errors ([#2471](https://github.com/rollup/rollup/pull/2471)) + +## 0.66.3 + +_2018-10-03_ + +- Detect side-effects in string.replace function arguments ([#2476](https://github.com/rollup/rollup/pull/2476)) +- Make sure chunk ids are assigned before creating output bundle ([#2483](https://github.com/rollup/rollup/pull/2483)) +- Use proper plugin name in error ([#2470](https://github.com/rollup/rollup/pull/2470)) +- Update TypeScript version and fix type errors ([#2488](https://github.com/rollup/rollup/pull/2488)) + +## 0.66.2 + +_2018-09-21_ + +- Add additional information to parse errors messages in JSON and other non-JS files ([#2466](https://github.com/rollup/rollup/pull/2466)) + +## 0.66.1 + +_2018-09-19_ + +- Ignore falsy plugins ([#2464](https://github.com/rollup/rollup/pull/2464)) +- Switch back to official TypeScript plugin ([#2465](https://github.com/rollup/rollup/pull/2465)) + +## 0.66.0 + +_2018-09-16_ + +- Support ES2019 optional catch bindings ([#2455](https://github.com/rollup/rollup/pull/2455)) +- Add option to transform paths within sourcemaps ([#2430](https://github.com/rollup/rollup/pull/2430)) +- Add renderStart and renderEnd plugin hooks ([#2438](https://github.com/rollup/rollup/pull/2438)) +- Expose ESM browser build and minify browser builds ([#2437](https://github.com/rollup/rollup/pull/2437) +- Associate hoisted variables in function bodys with function parameters ([#2456](https://github.com/rollup/rollup/pull/2456)) +- Fix issue when deconflicting variables used as pattern defaults ([#2446](https://github.com/rollup/rollup/pull/2446)) +- Properly deconflict default exported class and function expressions with ids ([#2458](https://github.com/rollup/rollup/pull/2458)) +- Faster internal test builds ([#2457](https://github.com/rollup/rollup/pull/2457)) +- Switch to rollup-plugin-typescript2 ([#2460](https://github.com/rollup/rollup/pull/2460)) +- Fix internal "perf" script ([#2433](https://github.com/rollup/rollup/pull/2433)) +- Test that errors are passed to the buildEnd hook ([#2450](https://github.com/rollup/rollup/pull/2450)) + +## 0.65.2 + +_2018-09-05_ + +- Prevent watch mode memory leak ([#2441](https://github.com/rollup/rollup/pull/2441)) + +## 0.65.1 + +_2018-09-05_ + +- Prevent globbing when using chokidar ([#2432](https://github.com/rollup/rollup/pull/2432)) + +## 0.65.0 + +_2018-08-25_ + +- Refactor and unify plugin system ([#2382](https://github.com/rollup/rollup/pull/2382)) +- Implement plugin cache API ([#2389](https://github.com/rollup/rollup/pull/2389)) +- Add watchChange plugin hook to watch changed files, deprecate asset dependencies ([#2405](https://github.com/rollup/rollup/pull/2405)) +- Refine asset handling ([#2369](https://github.com/rollup/rollup/pull/2369)) +- Implement `renderChunk` hook to replace `transformChunk` and `transformBundle` hooks ([#2406](https://github.com/rollup/rollup/pull/2406)) +- Add rollup version to plugin context ([#2394](https://github.com/rollup/rollup/pull/2394)) +- Do not resume stdin in watch mode to fix it for Lerna users ([#2410](https://github.com/rollup/rollup/pull/2410)) +- Allow `[format]` placeholder for id generation ([#2387](https://github.com/rollup/rollup/pull/2387)) +- Always log error stacks even when a code frame is given ([#2417](https://github.com/rollup/rollup/pull/2417)) +- Do not test module ids starting with `\0` as external ([#2400](https://github.com/rollup/rollup/pull/2400)) +- Fix tracing of namespace variables ([#2408](https://github.com/rollup/rollup/pull/2408)) +- Fix re-tracing of namespace variables ([#2420](https://github.com/rollup/rollup/pull/2420)) +- Properly wrap comment annotations in SystemJS exports ([#2408](https://github.com/rollup/rollup/pull/2408)) +- Fix renaming of destructured parameters ([#2419](https://github.com/rollup/rollup/pull/2419)) +- Do not display version in watch mode when using `--silent` ([#2392](https://github.com/rollup/rollup/pull/2392)) +- Make `cacheExpiry` an experimental option for now ([#2401](https://github.com/rollup/rollup/pull/2401)) +- Lint test configs on commit ([#2402](https://github.com/rollup/rollup/pull/2402)) +- Add code of conduct ([#2388](https://github.com/rollup/rollup/pull/2388)) +- Move to CircleCI ([#2390](https://github.com/rollup/rollup/pull/2390)) +- Update pull request template ([#2404](https://github.com/rollup/rollup/pull/2404)) + +## 0.64.1 + +_2018-08-07_ + +- Do not render initializers of hoisted variables in dead branches ([#2384](https://github.com/rollup/rollup/pull/2384)) + +## 0.64.0 + +_2018-08-07_ + +- Print memory consumption together with performance timings ([#2370](https://github.com/rollup/rollup/pull/2370)) +- Enable plugins to mark imports as external by returning false for resolveId ([#2351](https://github.com/rollup/rollup/pull/2351)) +- Always retain empty manual chunks ([#2362](https://github.com/rollup/rollup/pull/2362)) +- Ensure CLI warnings are shown on errors and add error for external id collisions ([#2334](https://github.com/rollup/rollup/pull/2334)) +- Remove unnecessary dependency, update dependencies, fix linting of test config ([#2376](https://github.com/rollup/rollup/pull/2376)) +- Add targeted Github issue templates ([#2356](https://github.com/rollup/rollup/pull/2356)) + +## 0.63.5 + +_2018-08-01_ + +- Ensure onwrite plugin hooks execute in sequence ([#2364](https://github.com/rollup/rollup/pull/2364)) +- Always warn when no name is provided for a global module ([#2359](https://github.com/rollup/rollup/pull/2359)) +- Add utility type for user created plugins ([#2355](https://github.com/rollup/rollup/pull/2355)) +- Remove deprecated es6 format from types ([#2349](https://github.com/rollup/rollup/pull/2349)) +- Mark inlineDynamicImports as optional in types ([#2348](https://github.com/rollup/rollup/pull/2348)) + +## 0.63.4 + +_2018-07-20_ + +- Use turbocolor instead of chalk ([#2339](https://github.com/rollup/rollup/pull/2339)) + +## 0.63.3 + +_2018-07-20_ + +- Handle expressions where "in" and "instanceof" are applied to primitive values ([#2344](https://github.com/rollup/rollup/pull/2344)) + +## 0.63.2 + +_2018-07-18_ + +- Fix bind order in for-of loops ([#2338](https://github.com/rollup/rollup/pull/2338)) + +## 0.63.1 + +_2018-07-18_ + +## 0.63.0 + +_2018-07-17_ + +- Fix many tree-shaking related issues ([#2315](https://github.com/rollup/rollup/pull/2315)) +- Add experimental support for top-level await ([#2235](https://github.com/rollup/rollup/pull/2235)) +- Prevent duplicate version printout in watch mode ([#2325](https://github.com/rollup/rollup/pull/2325)) +- Respect error frames provided by plugins ([#2309](https://github.com/rollup/rollup/pull/2309)) +- Add `esm` format alias to types ([#2327](https://github.com/rollup/rollup/pull/2327)) +- Further unify internal test setup ([#2329](https://github.com/rollup/rollup/pull/2329)) + +## 0.62.0 + +_2018-06-27_ + +- Add option to automatically shim missing exports ([#2118](https://github.com/rollup/rollup/pull/2118)) +- Inline dynamic imports that are also imported statically and only used in a single chunk ([#2295](https://github.com/rollup/rollup/pull/2295)) +- Handle caching and invalidation of assets ([#2267](https://github.com/rollup/rollup/pull/2267)) +- Fix plugin related types ([#2299](https://github.com/rollup/rollup/pull/2299)) + +## 0.61.2 + +_2018-06-23_ + +- Improve watcher error handling, only rebuild invalidated outputs ([#2296](https://github.com/rollup/rollup/pull/2296)) +- Update dependencies, make watcher more stable ([#2297](https://github.com/rollup/rollup/pull/2297)) + +## 0.61.1 + +_2018-06-21_ + +- Do not try to deconflict "undefined" ([#2291](https://github.com/rollup/rollup/pull/2291)) +- Properly track values for loop interator declarations and reassigned namespaces, add smoke test ([#2292](https://github.com/rollup/rollup/pull/2292)) + +## 0.61.0 + +_2018-06-20_ + +- Declare file dependencies via transform plugin hooks ([#2259](https://github.com/rollup/rollup/pull/2259)) +- Handle undefined values when evaluating conditionals ([#2264](https://github.com/rollup/rollup/pull/2264)) +- Handle known undefined properties when evaluating conditionals ([#2265](https://github.com/rollup/rollup/pull/2265)) +- Access watch events via the plugin context ([#2261](https://github.com/rollup/rollup/pull/2261)) +- Add option to suppress `__esModule` flag in output ([#2287](https://github.com/rollup/rollup/pull/2287)) +- Fix issue when re-declaring variables, track reassignments in more cases ([#2279](https://github.com/rollup/rollup/pull/2279)) +- Add VSCode debug settings ([#2276](https://github.com/rollup/rollup/pull/2276)) + +## 0.60.7 + +_2018-06-14_ + +- Fix typing issue ([#2269](https://github.com/rollup/rollup/pull/2269)) + +## 0.60.6 + +_2018-06-14_ + +- Track mutations of included virtual arrays ([#2263](https://github.com/rollup/rollup/pull/2263)) +- Update readme ([#2266](https://github.com/rollup/rollup/pull/2266)) + +## 0.60.5 + +_2018-06-14_ + +- Track deep reassignments of global and exported variables and improve performance ([#2254](https://github.com/rollup/rollup/pull/2254)) + +## 0.60.4 + +_2018-06-13_ + +- Properly handle initially uninitialized exports and exports of globals in SystemJS output ([#2258](https://github.com/rollup/rollup/pull/2258)) + +## 0.60.3 + +_2018-06-13_ + +- Fix types to allow watching an array of outputs ([#2262](https://github.com/rollup/rollup/pull/2262)) + +## 0.60.2 + +_2018-06-11_ + +- Permit setting an asset's source in `generateBundle` ([#2256](https://github.com/rollup/rollup/pull/2256)) +- Add automatic linting ([#2242](https://github.com/rollup/rollup/pull/2242)) + +## 0.60.1 + +_2018-06-07_ + +- Fix plugin regressions ([#2246](https://github.com/rollup/rollup/pull/2246)) +- Avoid conflicts for large numbers of variables ([#2244](https://github.com/rollup/rollup/pull/2244)) + +## 0.60.0 + +_2018-06-06_ + +- New plugin hooks: transformChunk, buildStart, buildEnd; extended plugin context with warn, error, resolveId, isExternal, emitAsset, setAssetSource and getAssetFileName available to any hook ([#2208](https://github.com/rollup/rollup/pull/2208)) +- [BREAKING] Deprecate the `legacy` option and thus IE8 support ([#2141](https://github.com/rollup/rollup/pull/2141)) +- Detect more known extensions and load .mjs without extension ([#2211](https://github.com/rollup/rollup/pull/2211)) +- Add compact output mode ([#2151](https://github.com/rollup/rollup/pull/2151)) +- Significantly improve sourcemap generation performance ([#2228](https://github.com/rollup/rollup/pull/2228)) +- Enable naming SystemJS modules ([#2028](https://github.com/rollup/rollup/pull/2028)) +- Do not use alternate screen if clearScreen is set in watch mode ([#2125](https://github.com/rollup/rollup/pull/2125)) +- Allow object input form for code-splitting in watch mode ([#2217](https://github.com/rollup/rollup/pull/2217)) +- Track reassignments of methods of exports from outside ([#2240](https://github.com/rollup/rollup/pull/2240)) +- Preserve id of default exported functions and classes ([#2234](https://github.com/rollup/rollup/pull/2234)) +- Add semicolons after default exports ([#2209](https://github.com/rollup/rollup/pull/2209)) +- Fix build problems on Windows ([#2232](https://github.com/rollup/rollup/pull/2232)) +- Display install size in readme ([#2196](https://github.com/rollup/rollup/pull/2196)) +- Improve preserve modules test ([#2236](https://github.com/rollup/rollup/pull/2236)) + +## 0.59.4 + +_2018-05-28_ + +- Fix performance regression when many return statements are used ([#2218](https://github.com/rollup/rollup/pull/2218)) + +## 0.59.3 + +_2018-05-24_ + +- Fix reassignment tracking for constructor parameters ([#2214](https://github.com/rollup/rollup/pull/2214)) + +## 0.59.2 + +_2018-05-21_ + +- Fix reassignment tracking in for-in loops ([#2205](https://github.com/rollup/rollup/pull/2205)) + +## 0.59.1 + +_2018-05-16_ + +- Fix infinite recursion when determining literal values of circular structures ([#2193](https://github.com/rollup/rollup/pull/2193)) +- Fix invalid code when simplifying expressions without spaces ([#2194](https://github.com/rollup/rollup/pull/2194)) + +## 0.59.0 + +_2018-05-15_ + +- Tree-shake statically analysable dynamic conditionals ([#2167](https://github.com/rollup/rollup/pull/2167)) +- Do not emit empty chunks when code-splitting or empty files when preserving modules ([#2128](https://github.com/rollup/rollup/pull/2128)) +- Support `import.meta.url` ([#2164](https://github.com/rollup/rollup/pull/2164)) +- Add `esm` format alias ([#2102](https://github.com/rollup/rollup/pull/2102)) +- Use alphanumeric base64 characters when deconflicting variables ([#2188](https://github.com/rollup/rollup/pull/2188)) +- Improve handling of external modules imported as both default and named imports ([#2136](https://github.com/rollup/rollup/pull/2136)) +- Properly deconflict named imports from other chunks ([#2177](https://github.com/rollup/rollup/pull/2177)) +- Fix an issue with namespaces containing reexports ([#2157](https://github.com/rollup/rollup/pull/2157)) +- Fix an issue with with incorrectly mapped default exports when code-splitting CJS or AMD modules ([#2178](https://github.com/rollup/rollup/pull/2178)) +- Fix an issue with wrong paths of relative external imports ([#2160](https://github.com/rollup/rollup/pull/2160)) +- Fix an issue when using default exports and `interop: false` ([#2149](https://github.com/rollup/rollup/pull/2149)) +- Fix in issue with invalid syntax in SystemJS output ([#2187](https://github.com/rollup/rollup/pull/2187)) +- Fix an issue when tree-shaking call expressions and reassigned variables ([#2186](https://github.com/rollup/rollup/pull/2186)) +- Fix file paths in source maps ([#2161](https://github.com/rollup/rollup/pull/2161)) +- Fix wrong file name in error message ([#2137](https://github.com/rollup/rollup/pull/2137)) +- Always use npm 5 on CI ([#2185](https://github.com/rollup/rollup/pull/2185)) + +## 0.58.2 + +_2018-04-23_ + +- Fix rendering of certain statically resolvable if statements ([#2146](https://github.com/rollup/rollup/pull/2146)) + +## 0.58.1 + +_2018-04-18_ + +- Fix comment detection ([#2129](https://github.com/rollup/rollup/pull/2129)) + +## 0.58.0 + +_2018-04-16_ + +- Support individual chunk names with optional content hashes ([#2068](https://github.com/rollup/rollup/pull/2068)) +- Support manually created chunks ([#2084](https://github.com/rollup/rollup/pull/2084)) +- Automatically import deep dependencies when code splitting for better performance ([#2073](https://github.com/rollup/rollup/pull/2073)) +- Automatically minify internal export/import names for esm and system output ([#2087](https://github.com/rollup/rollup/pull/2087)) +- Add option to automatically merge small chunks ([#2090](https://github.com/rollup/rollup/pull/2090)) +- Significantly improve tree-shaking performance ([#2119](https://github.com/rollup/rollup/pull/2119)) +- Enable tree-shaking for logical expressions ([#2098](https://github.com/rollup/rollup/pull/2098)) +- Rework external types and reduce type related dependencies ([#2108](https://github.com/rollup/rollup/pull/2108)) +- Support parallel dependency resolution ([#2116](https://github.com/rollup/rollup/pull/2116)) +- Improve deprecation handling ([#2076](https://github.com/rollup/rollup/pull/2076)) +- Enable `--perf` timings in watch mode ([#2065](https://github.com/rollup/rollup/pull/2065)) +- Improve performance timers ([#2111](https://github.com/rollup/rollup/pull/2111)) +- Improve error handling for plugins ([#2100](https://github.com/rollup/rollup/pull/2100)) +- Improve error when using `--dir` in a single file build ([#2123](https://github.com/rollup/rollup/pull/2123)) +- Do not warn for external imports that are unused due to tree-shaking ([#2124](https://github.com/rollup/rollup/pull/2124)) +- Update mixed export warning message ([#2107](https://github.com/rollup/rollup/pull/2107)) +- Remove duplicate badges from readme ([#2083](https://github.com/rollup/rollup/pull/2083)) +- Update readme examples ([#2086](https://github.com/rollup/rollup/pull/2086)) + +## 0.57.1 + +_2018-03-17_ + +- Improve sourcemap generation performance ([#2062](https://github.com/rollup/rollup/pull/2062)) +- Add reserved config option namespace and improve CLI interface ([#2063](https://github.com/rollup/rollup/pull/2063)) +- Fix issue with default exported function and class expressions ([#2059](https://github.com/rollup/rollup/pull/2059)) +- Replace `forEach` with faster `for` loops in some places ([#2064](https://github.com/rollup/rollup/pull/2064)) + +## 0.57.0 + +_2018-03-15_ + +- Add option to preserve the module structure instead of bundling ([#1922](https://github.com/rollup/rollup/pull/1922)) +- Enable watch mode when code-splitting ([#2035](https://github.com/rollup/rollup/pull/2035)) +- Optionally pass CLI commands to config file ([#1926](https://github.com/rollup/rollup/pull/1926)) +- Option to add correct `.toString` tags to namespaces ([#2041](https://github.com/rollup/rollup/pull/2041)) +- Option and scripts to display performance timings ([#2045](https://github.com/rollup/rollup/pull/2045)) +- Fixes for exported or early accessed namespaces + improved namespace indentation ([#2041](https://github.com/rollup/rollup/pull/2041)) +- Include missing TypeScript dependencies ([#1965](https://github.com/rollup/rollup/pull/1965)) +- Add #\_PURE annotation to frozen namespaces ([#2044](https://github.com/rollup/rollup/pull/2044)) +- Improve sourcemap and tree-shaking performance ([#2052](https://github.com/rollup/rollup/pull/2052)) +- Inline sourcemap lookups and make rollup smaller ([#2055](https://github.com/rollup/rollup/pull/2055)) +- Use updated magic-string types ([#2057](https://github.com/rollup/rollup/pull/2057)) +- [BREAKING] Revert class id preservation from #2025 ([#2048](https://github.com/rollup/rollup/pull/2048)) +- [BREAKING] Refactor missing export plugin hook ([#1987](https://github.com/rollup/rollup/pull/1987)) + +## 0.56.5 + +_2018-03-07_ + +- Preserve ids when deconflicting classes ([#2025](https://github.com/rollup/rollup/pull/2025)) +- Fix an issue with re-exported namespace imports ([#2034](https://github.com/rollup/rollup/pull/2034)) +- Prevent an infinite loop when binding member expressions ([#1963](https://github.com/rollup/rollup/pull/1963)) +- Convert code style via prettier ([#2031](https://github.com/rollup/rollup/pull/2031)) +- Fix links in documentation ([#2026](https://github.com/rollup/rollup/pull/2026)) + +## 0.56.4 + +_2018-03-05_ + +- Make rollup builds reproducible ([#2024](https://github.com/rollup/rollup/pull/2024)) +- Improve error handling for source maps ([#2012](https://github.com/rollup/rollup/pull/2012)) +- Properly handle SystemJS default exports without semicolons ([#2019](https://github.com/rollup/rollup/pull/2019)) +- Properly handle importing the same variable several times when code-splitting ([#2020](https://github.com/rollup/rollup/pull/2020)) +- Improve re-export tracing ([#2021](https://github.com/rollup/rollup/pull/2021)) +- Apply "prettier" on commit ([#2017](https://github.com/rollup/rollup/pull/2017)) +- Automatically clean up outdated tests ([#2009](https://github.com/rollup/rollup/pull/2009)) +- Add SystemJS output to form tests ([#2022](https://github.com/rollup/rollup/pull/2022)) +- Improve internal build configuration ([#2016](https://github.com/rollup/rollup/pull/2016)) + +## 0.56.3 + +_2018-02-25_ + +- Fix issues around default exports and module facades ([#2001](https://github.com/rollup/rollup/pull/2001)) +- Improve and fix internal chunk interface ([#1994](https://github.com/rollup/rollup/pull/1994)) +- Fix superfluous semicolons added after declarations ([#1999](https://github.com/rollup/rollup/pull/1999)) +- Improve code-splitting tests ([#1990](https://github.com/rollup/rollup/pull/1990)) + +## 0.56.2 + +_2018-02-19_ + +- Fix handling of reassigned default exports ([#1975](https://github.com/rollup/rollup/pull/1975)) +- Fix handling of renamed exports in entry points ([#1977](https://github.com/rollup/rollup/pull/1977)) +- Update internal TypeScript version ([#1980](https://github.com/rollup/rollup/pull/1980)) +- Omit compiled source files from published types ([#1981](https://github.com/rollup/rollup/pull/1981)) +- Fix example in readme file ([#1984](https://github.com/rollup/rollup/pull/1984)) +- Fix non-replaced dynamic imports in non-ESM output ([#1985](https://github.com/rollup/rollup/pull/1985)) + +## 0.56.1 + +_2018-02-16_ + +- Fix regression when rendering switch statements ([#1971](https://github.com/rollup/rollup/pull/1971)) + +## 0.56.0 + +_2018-02-15_ + +- Update to ECMAScript 2018 ([#1953](https://github.com/rollup/rollup/pull/1953)) +- Rework tree-shaking rendering algorithm ([#1949](https://github.com/rollup/rollup/pull/1949)) +- Tree-shake pure prototype calls on literals ([#1916](https://github.com/rollup/rollup/pull/1916)) +- Expose AST parser to plugins ([#1945](https://github.com/rollup/rollup/pull/1945)) +- Fix namespace re-export deconflicting ([#1960](https://github.com/rollup/rollup/pull/1960)) +- Allow globals to be re-exported ([#1959](https://github.com/rollup/rollup/pull/1959)) +- Fix internal performance timers ([#1966](https://github.com/rollup/rollup/pull/1966)) + +## 0.55.5 + +_2018-02-10_ + +- Remove OpenCollective dependency ([#1915](https://github.com/rollup/rollup/pull/1915)) + +## 0.55.4 + +_2018-02-09_ + +- Improve name deconflicting of external variables ([#1930](https://github.com/rollup/rollup/pull/1930)) +- Improve re-export handling ([#1947](https://github.com/rollup/rollup/pull/1947)) +- Mark preserveSymlinks option as optional ([#1939](https://github.com/rollup/rollup/pull/1939)) +- Enable code-splitting tests to check directory structures ([#1924](https://github.com/rollup/rollup/pull/1924)) +- Improve TypeScript definition test ([#1954](https://github.com/rollup/rollup/pull/1954)) + +## 0.55.3 + +_2018-02-01_ + +- Remove OpenCollective dependency ([#1915](https://github.com/rollup/rollup/pull/1915)) + +## 0.55.2 + +_2018-02-01_ + +- Add option to not follow symlinks ([#1819](https://github.com/rollup/rollup/pull/1819)) +- Fix crash in windows shell ([#1928](https://github.com/rollup/rollup/pull/1928)) +- Fix and test for external TypeScript errors ([#1903](https://github.com/rollup/rollup/pull/1903)) +- Activate OpenCollective ([#1915](https://github.com/rollup/rollup/pull/1915)) +- Optimize CI scripts ([#1921](https://github.com/rollup/rollup/pull/1921)) + +## 0.55.1 + +_2018-01-26_ + +- Improve dynamic import workflow ([#1907](https://github.com/rollup/rollup/pull/1907)) +- Properly handle multiple dynamic imports of the same module ([#1911](https://github.com/rollup/rollup/pull/1911)) +- Fix import specifier deshadowing ([#1912](https://github.com/rollup/rollup/pull/1912)) +- Allow plugin load hook to return an empty string ([#1908](https://github.com/rollup/rollup/pull/1908)) +- Let onwarn handler accept strings ([#1905](https://github.com/rollup/rollup/pull/1905)) + +## 0.55.0 + +_2018-01-23_ + +- Support code splitting ([#1841](https://github.com/rollup/rollup/pull/1841)) +- Support SystemJS as output format ([#1897](https://github.com/rollup/rollup/pull/1897)) +- Allow injecting acorn plugins ([#1857](https://github.com/rollup/rollup/pull/1857)) +- Add `missingExport` plugin hook ([#1845](https://github.com/rollup/rollup/pull/1845)) +- No longer parse config files via bublé ([#1899](https://github.com/rollup/rollup/pull/1899)) +- Use externally maintained dynamic import acorn plugin ([#1891](https://github.com/rollup/rollup/pull/1891)) +- Fix an error message ([#1886](https://github.com/rollup/rollup/pull/1886)) +- Refactor internal rendering options ([#1900](https://github.com/rollup/rollup/pull/1900)) +- Extract internal path resolution ([#1879](https://github.com/rollup/rollup/pull/1879)) +- Extract internal bundle option handling ([#1880](https://github.com/rollup/rollup/pull/1880)) +- Add import description type ([#1884](https://github.com/rollup/rollup/pull/1884)) +- Clean up watch options types ([#1860](https://github.com/rollup/rollup/pull/1860)) +- Clean up some tests ([#1888](https://github.com/rollup/rollup/pull/1888)) + +## 0.54.1 + +_2018-01-17_ + +- Fix TypeScript errors in emitted type definitions ([#1871](https://github.com/rollup/rollup/pull/1871)) + +## 0.54.0 + +_2018-01-12_ + +- Automatically inline locally resolvable dynamic imports ([#1816](https://github.com/rollup/rollup/pull/1816)) +- Preserve directives in function bodies ([#1856](https://github.com/rollup/rollup/pull/1856)) +- Refactor an error notification ([#1846](https://github.com/rollup/rollup/pull/1846)) +- Refactor a wrong import ([#1863](https://github.com/rollup/rollup/pull/1863)) +- Improve emitted TypeScript definitions ([#1864](https://github.com/rollup/rollup/pull/1864)) +- Refactor unused import ([#1866](https://github.com/rollup/rollup/pull/1866)) + +## 0.53.4 + +_2018-01-10_ + +- More type cleanup ([#1858](https://github.com/rollup/rollup/pull/1858)) +- Use chalks internal helper to detect if colors should be used ([#1853](https://github.com/rollup/rollup/pull/1853)) +- Refactor entity handling to use interfaces ([#1840](https://github.com/rollup/rollup/pull/1840)) +- Use immutable.js internal types ([#1844](https://github.com/rollup/rollup/pull/1844)) +- Ship `TypeScript` declaration files ([#1837](https://github.com/rollup/rollup/pull/1837)) + +## 0.53.3 + +_2018-01-02_ + +- Use correct name when re-exporting from external modules ([#1794](https://github.com/rollup/rollup/pull/1794)) +- Disable warnings when `resolveId` returns false ([#1825](https://github.com/rollup/rollup/pull/1825)) + +## 0.53.2 + +_2017-12-30_ + +- Properly handle output arrays in the JavaScript API ([#1827](https://github.com/rollup/rollup/pull/1827)) + +## 0.53.1 + +_2017-12-28_ + +- Properly deprecate more config options ([#1812](https://github.com/rollup/rollup/pull/1812)) +- Pass output options to `transformBundle` plugin hook ([#1813](https://github.com/rollup/rollup/pull/1813)) + +## 0.53.0 + +_2017-12-22_ + +- Experimental dynamic import support ([#1790](https://github.com/rollup/rollup/pull/1790)) +- Unify config validation ([#1805](https://github.com/rollup/rollup/pull/1805)) + +## 0.52.3 + +_2017-12-19_ + +- Properly hoist default exported functions in more situations ([#1799](https://github.com/rollup/rollup/pull/1799)) +- Allow plugin transformations to not overwrite source maps by returning null ([#1797](https://github.com/rollup/rollup/pull/1797)) +- Provide more parameters to "external" handler ([#1792](https://github.com/rollup/rollup/pull/1792)) + +## 0.52.2 + +_2017-12-15_ + +- No longer ignore side-effects in JSON.parse and JSON.stringify ([#1785](https://github.com/rollup/rollup/pull/1785)) +- Updated links in warnings ([#1776](https://github.com/rollup/rollup/pull/1776)) +- No longer prevent self-imports ([#1777](https://github.com/rollup/rollup/pull/1777)) +- Properly hoist default exported functions ([#1787](https://github.com/rollup/rollup/pull/1787)) +- Prevent corruption when re-exporting default exports ([#1765](https://github.com/rollup/rollup/pull/1765)) + +## 0.52.1 + +_2017-12-05_ + +- Improve deprecation warnings ([#1765](https://github.com/rollup/rollup/pull/1765)) +- Properly use stdin ([#1774](https://github.com/rollup/rollup/pull/1774)) +- Let --environment be used multiple times ([#1768](https://github.com/rollup/rollup/pull/1768)) +- Always transpile config files ([#1759](https://github.com/rollup/rollup/pull/1759)) +- Respect globals option in headers of UMD and IIFE files ([#1747](https://github.com/rollup/rollup/pull/1747)) + +## 0.52.0 + +_2017-11-25_ + +- Accept config as promise ([#1731](https://github.com/rollup/rollup/pull/1731)) +- Accept promises for intro/outro/banner/footer ([#1253](https://github.com/rollup/rollup/pull/1253)) +- Option to prevent freezing of namespace imports ([#1696](https://github.com/rollup/rollup/pull/1696)) +- Option to retain all output in watch mode ([#1688](https://github.com/rollup/rollup/pull/1688)) +- Options to fine-tune treeshaking ([#1760](https://github.com/rollup/rollup/pull/1760)) + +## 0.51.8 + +_2017-11-19_ + +- Fix speed problems by simplifying treeshaking reassignment handling ([#1740](https://github.com/rollup/rollup/pull/1740)) +- Update dependencies ([#1742](https://github.com/rollup/rollup/pull/1742)) + +## 0.51.7 + +_2017-11-17_ + +- Keep "this"-context when calling sequence expressions ([#1724](https://github.com/rollup/rollup/pull/1724)) + +## 0.51.6 + +_2017-11-16_ + +- Use sourcemaps to determine error locations ([#1728](https://github.com/rollup/rollup/pull/1728)) + +## 0.51.5 + +_2017-11-11_ + +- Fix regressions with uninitialised conditional expressions ([#1720](https://github.com/rollup/rollup/pull/1720)) + +## 0.51.4 + +_2017-11-11_ + +- Fix regressions preventing builds ([#1725](https://github.com/rollup/rollup/pull/1725)) + +## 0.51.3 + +_2017-11-10_ + +- Fix regression when treeshaking sequence expressions ([#1717](https://github.com/rollup/rollup/pull/1717)) + +## 0.51.2 + +_2017-11-09_ + +- Fix treeshaking regression when labels are used inside functions ([#1712](https://github.com/rollup/rollup/pull/1712)) + +## 0.51.1 + +_2017-11-08_ + +- Fix an issue with empty return statements ([#1704](https://github.com/rollup/rollup/pull/1704)) + +## 0.51.0 + +_2017-11-08_ + +- Massive improvements to the treeshaking algorithm ([#1667](https://github.com/rollup/rollup/pull/1667)) + +## 0.50.1 + +_2017-11-08_ + +- Fix treeshaking regression ([#1695](https://github.com/rollup/rollup/pull/1695)) +- Treeshaking improvements ([#1650](https://github.com/rollup/rollup/pull/1650)) +- Enable installation from Github ([#1670](https://github.com/rollup/rollup/pull/1670)) +- Update documentation ([#1660](https://github.com/rollup/rollup/pull/1660)) + +## 0.50.0 + +_2017-09-16_ + +- Many treeshaking improvements ([#1624](https://github.com/rollup/rollup/pull/1624)) +- Show finish time in watch mode ([#1620](https://github.com/rollup/rollup/pull/1620)) + +## 0.49.3 + +_2017-09-08_ + +- Respect `watch` options ([#1596](https://github.com/rollup/rollup/issues/1596)) +- Fix treeshaking regressions ([#1604](https://github.com/rollup/rollup/pull/1604)) +- Allow `-o` to work with `output.format` ([#1606](https://github.com/rollup/rollup/pull/1606)) + +## 0.49.2 + +_2017-08-29_ + +- Fix treeshaking regressions ([#1591](https://github.com/rollup/rollup/pull/1591)) + +## 0.49.1 + +_2017-08-28_ + +- Fix treeshaking regressions ([#1586](https://github.com/rollup/rollup/pull/1586)) + +## 0.49.0 + +_2017-08-27_ + +- Completely update the treeshaking algorithm ([#1582](https://github.com/rollup/rollup/pull/1582)) +- Only flip screen buffer if appropriate ([#1574](https://github.com/rollup/rollup/pull/1574)) +- Guard against two instances creating the same dir ([#1576](https://github.com/rollup/rollup/pull/1576)) + +## 0.48.2 + +- Paths is an output option ([#1569](https://github.com/rollup/rollup/pull/1569)) + +## 0.48.1 + +- Print deprecation warnings in watch mode, and fix options when watcher restarts ([#1568](https://github.com/rollup/rollup/pull/1568)) + +## 0.48.0 + +- Numerous changes to the `options` object and CLI arguments ([#1479](https://github.com/rollup/rollup/issues/1479)). See [this gist](https://gist.github.com/Rich-Harris/d472c50732dab03efeb37472b08a3f32) for a rundown. + +## 0.47.6 + +- Set `process.env.ROLLUP_WATCH` _before_ loading config file + +## 0.47.5 + +- Fix broken multi-bundle configs with `rollup.watch` ([#1532](https://github.com/rollup/rollup/issues/1532)) + +## 0.47.4 + +- Delete cached config file before reloading in watch mode + +## 0.47.3 + +- Deshadow aliased imports ([#1550](https://github.com/rollup/rollup/issues/1550)) + +## 0.47.2 + +- Rebuild with dependency that npm randomly deleted + +## 0.47.1 + +- Ignore external namespace imports when deshadowing ([#1547](https://github.com/rollup/rollup/issues/1547)) + +## 0.47.0 + +- Watch config file, restart `rollup.watch` on change ([#1535](https://github.com/rollup/rollup/issues/1535)) +- Correctly render `export { foo } from` declarations in `es` output ([#1543](https://github.com/rollup/rollup/pull/1543)) +- Reinstate missing `rollup.VERSION` + +## 0.46.3 + +- init for/for-of loop section head with correct scopes ([#1538](https://github.com/rollup/rollup/issues/1538), [#1539](https://github.com/rollup/rollup/issues/1539)) +- Fix namespace imports and re-exports in `es` output ([#1511](https://github.com/rollup/rollup/issues/1511)) +- Deshadow indirectly imported namespaces ([#1488](https://github.com/rollup/rollup/issues/1488), [#1505](https://github.com/rollup/rollup/issues/1505)) + +## 0.46.2 + +- Pass options to `bundle.write` correctly in `rollup.watch` ([#1533](https://github.com/rollup/rollup/issues/1533)) +- init for-in loop section head with correct scopes ([#1480](https://github.com/rollup/rollup/issues/1480)) +- support `--no-interop` flag ([#1524](https://github.com/rollup/rollup/issues/1524)) + +## 0.46.1 + +- Remove `rollup.watch` from browser build ([#1530](https://github.com/rollup/rollup/issues/1530)) +- Remove `source-map-support` dependency ([#1528](https://github.com/rollup/rollup/issues/1528)) + +## 0.46.0 + +- `options.format` is now required ([#1491](https://github.com/rollup/rollup/pull/1491)) +- if `options.format` is `es6`, it will now throw an error (should be `es`) ([#1491](https://github.com/rollup/rollup/pull/1491)) +- Add experimental `rollup.watch` method, replacing [rollup-watch](https://github.com/rollup/rollup-watch) ([#1491](https://github.com/rollup/rollup/pull/1491)) +- Batch warnings together in CLI output ([#1491](https://github.com/rollup/rollup/pull/1491)) +- Clear screen between rebuilds in `--watch` mode ([#1491](https://github.com/rollup/rollup/pull/1491)) +- `onwarn` function's second argument is the default handler, allowing easier filtering without reimplementing any logic ([#1491](https://github.com/rollup/rollup/pull/1491)) +- Prevent semi-colon removal after variable declaration that is for loop body ([#1275](https://github.com/rollup/rollup/issues/1275)) +- Return `exports` for namespaced but non-extended IIFE bundles ([#1492](https://github.com/rollup/rollup/issues/1492)) +- Fix scoping in switch statements ([#1498](https://github.com/rollup/rollup/pull/1498)) +- Handle side-effects in tagged template expressions ([#1508](https://github.com/rollup/rollup/pull/1508)) +- More descriptive error for missing options.format ([#1510](https://github.com/rollup/rollup/pull/1510)) +- Refactor scope handling ([#1517](https://github.com/rollup/rollup/pull/1517)) +- Handle failure of a config in multi-config build ([#1513](https://github.com/rollup/rollup/issues/1513)) + +## 0.45.2 + +- Fix interop when import is a string ([#1486](https://github.com/rollup/rollup/issues/1486)) +- Separate `resolvedIds` from `resolvedExternalIds` ([#1490](https://github.com/rollup/rollup/pull/1490)) +- Add `--extend` flag to CLI ([#1482](https://github.com/rollup/rollup/pull/1482)) + +## 0.45.1 + +- Remove `weak` from `optionalDependencies` ([#1483](https://github.com/rollup/rollup/issues/1483)) + +## 0.45.0 + +- [BREAKING] `bundle.generate(...)` returns a Promise, so that `transformBundle` plugin hooks can be asynchronous ([#1474](https://github.com/rollup/rollup/issues/1474)) + +## 0.44.0 + +- [BREAKING] Don't extend existing globals, unless `options.extend` is true ([#827](https://github.com/rollup/rollup/issues/827)) +- Fix handling of catch clause parameters ([#1462](https://github.com/rollup/rollup/issues/1462)) + +## 0.43.1 + +- Fix memory leak on incremental rebuilds ([#883](https://github.com/rollup/rollup/issues/883)) +- Allow `this.warn` and `this.error` to accept a `{line, column}` object as an alternative to a character index ([#1265](https://github.com/rollup/rollup/issues/1265)) +- Print more useful error if entry module is 'external' ([#1264](https://github.com/rollup/rollup/issues/1264)) +- Catch errors in `bundle.generate` options ([#1463](https://github.com/rollup/rollup/pull/1463)) +- Fix magic-string deprecation warning ([#1445](https://github.com/rollup/rollup/pull/1445)) + +## 0.43.0 + +- Allow config files to import JSON ([#1426](https://github.com/rollup/rollup/issues/1426)) +- Allow undefined imports in interop block ([#1341](https://github.com/rollup/rollup/issues/1341)) +- Add `process.env.ROLLUP_WATCH = 'true'` in watch mode ([#1429](https://github.com/rollup/rollup/issues/1429)) +- Add `pureExternalModules` option ([#1352](https://github.com/rollup/rollup/issues/1352)) +- Allow plugins to specify `options.entry` ([#1270](https://github.com/rollup/rollup/issues/1270)) +- Update dependencies + +## 0.42.0 + +- Deprecate `options.moduleId` in favour of `options.amd.id` ([#1365](https://github.com/rollup/rollup/pull/1365)) +- Add `options.amd.define` option to specify name of AMD `define` function ([#1365](https://github.com/rollup/rollup/pull/1365)) +- Fix incorrect class removal with `treeshake: false` ([#1375](https://github.com/rollup/rollup/pull/1375)) +- Deconflict module exports imported as namespaces ([#1384](https://github.com/rollup/rollup/issues/1384)) +- Handle bare self-imports ([#1274](https://github.com/rollup/rollup/issues/1274)) +- Allow config file to export an array of multiple configs ([#1389](https://github.com/rollup/rollup/pull/1389)) +- Handle exponentiation operator, and fail gracefully on unknown operators ([#1416](https://github.com/rollup/rollup/issues/1416)) +- Add `watch` option ([#1424](https://github.com/rollup/rollup/pull/1424)) + +## 0.41.6 + +- Preserve `originalSourceMap` on incremental rebuilds for loaders with sourcemaps ([#1336](https://github.com/rollup/rollup/issues/1336)) + +## 0.41.5 + +- Wrap ternary consequent/alternate sequences in parens ([#1273](https://github.com/rollup/rollup/issues/1273)) +- Fix erroneous warning on multiple `export * from` declarations with defaults ([#1278](https://github.com/rollup/rollup/issues/1278)) +- Prevent variable conflicts with `treeshake: false` ([#1268](https://github.com/rollup/rollup/issues/1268)) +- Allow missing `source` when collapsing sourcemaps ([#1254](https://github.com/rollup/rollup/issues/1254)) +- Allow plugins to log with strings ([#1316](https://github.com/rollup/rollup/pull/1316)) + +## 0.41.4 + +- Fix cases of multiple `export * from 'external'` declarations ([#1252](https://github.com/rollup/rollup/issues/1252)) +- Fix 'TODO' error message ([#1257](https://github.com/rollup/rollup/issues/1257)) + +## 0.41.3 + +- Don't treat `this.foo` as possible namespace ([#1258](https://github.com/rollup/rollup/issues/1258)) + +## 0.41.2 + +- Optimize `namespace['foo']` references ([#1240](https://github.com/rollup/rollup/pull/1240)) + +## 0.41.1 + +- Include `new` expressions where callee is a class with side-effects ([#980](https://github.com/rollup/rollup/issues/980) [#1233](https://github.com/rollup/rollup/issues/1233)) + +## 0.41.0 + +- Add `this.warn(...)` and `this.error(...)` methods to plugin `transform` hook contexts ([#1140](https://github.com/rollup/rollup/issues/1140)) +- `throw` always considered to be a side effect ([#1227](https://github.com/rollup/rollup/pull/1227)) + +## 0.40.2 + +- Add `file` property to sourcemaps for bundles with plugins ([#986](https://github.com/rollup/rollup/issues/986)) +- Don't require globals for empty imports ([#1217](https://github.com/rollup/rollup/issues/1217)) + +## 0.40.1 + +- Allow missing space between `export default` and declaration ([#1218](https://github.com/rollup/rollup/pull/1218)) + +## 0.40.0 + +- [BREAKING] Better, more consistent error logging ([#1212](https://github.com/rollup/rollup/pull/1212)) +- Don't use colours and emojis for non-TTY stderr ([#1201](https://github.com/rollup/rollup/issues/1201)) + +## 0.39.2 + +- Prevent mutation of cached ASTs (fixes stack overflow with rollup-watch) ([#1205](https://github.com/rollup/rollup/pull/1205)) + +## 0.39.1 + +- Ignore `var` initialisers in dead branches ([#1198](https://github.com/rollup/rollup/issues/1198)) + +## 0.39.0 + +- [BREAKING] Warnings are objects, rather than strings ([#1194](https://github.com/rollup/rollup/issues/1194)) + +## 0.38.3 + +- More informative warning for implicit external dependencies ([#1051](https://github.com/rollup/rollup/issues/1051)) +- Warn when creating browser bundle with external dependencies on Node built-ins ([#1051](https://github.com/rollup/rollup/issues/1051)) +- Statically analyse LogicalExpression nodes, for better dead code removal ([#1061](https://github.com/rollup/rollup/issues/1061)) + +## 0.38.2 + +- Preserve `var` declarations in dead branches ([#997](https://github.com/rollup/rollup/issues/997)) +- Warn if exporting a call expression that looks like a function declaration ([#1011](https://github.com/rollup/rollup/issues/1011)) +- Wrap function expressions in parentheses if necessary ([#1011](https://github.com/rollup/rollup/issues/1011)) + +## 0.38.1 + +- Fix sourcemap comment removal ([#1104](https://github.com/rollup/rollup/issues/1104)) +- Warn if empty bundle is generated ([#444](https://github.com/rollup/rollup/issues/444)) +- Support ES2017 syntax ([#492](https://github.com/rollup/rollup/issues/492)) +- Remove unused imports from external modules ([#595](https://github.com/rollup/rollup/issues/595)) +- Remove unused function and class declarations inside function bodies ([#1108](https://github.com/rollup/rollup/issues/1108), [#1178](https://github.com/rollup/rollup/issues/1178)) +- Deconflict function expression IDs ([#1176](https://github.com/rollup/rollup/issues/1176)) + +## 0.38.0 + +- [BREAKING] `export { foo as default }` creates live binding ([#1078](https://github.com/rollup/rollup/issues/1078)) +- Prevent sourceMappingURL removal edge case ([#988](https://github.com/rollup/rollup/issues/988)) +- Bind function expression IDs to the correct scope ([#1083](https://github.com/rollup/rollup/issues/1083)) +- Correctly deshadow destructured parameters with assignments ([#1008](https://github.com/rollup/rollup/issues/1008)) + +## 0.37.2 + +- Remove unused `new` expressions without side-effects ([#179](https://github.com/rollup/rollup/issues/179)) +- Only remove valid sourceMappingURL comments ([#1132](https://github.com/rollup/rollup/issues/1132)) +- Ensure blocks containing activated `var` declarations are included in output ([#1113](https://github.com/rollup/rollup/issues/1113)) +- Support plugin outros ([#1116](https://github.com/rollup/rollup/issues/1116)) + +## 0.37.1 + +- Follow symlinks ([#447](https://github.com/rollup/rollup/issues/447)) +- Fix tree-shaking of recursive functions and other cases ([#1120](https://github.com/rollup/rollup/issues/1120), [#1142](https://github.com/rollup/rollup/issues/1142)) +- Support module names that require quotes ([#582](https://github.com/rollup/rollup/issues/582), [#584](https://github.com/rollup/rollup/issues/584)) +- Fix [#957](https://github.com/rollup/rollup/issues/957) + +## 0.37.0 + +- [BREAKING] Default exports are not included in reified namespaces ([#1028](https://github.com/rollup/rollup/issues/1028)) +- Parentheses do not defeat tree-shaking ([#1101](https://github.com/rollup/rollup/issues/1101), [#1128](https://github.com/rollup/rollup/issues/1128)) +- More `legacy` fixes: do not create getters ([#1069](https://github.com/rollup/rollup/pull/1069)), do not include `__esModule` ([#1068](https://github.com/rollup/rollup/pull/1068)), quote reserved property names ([#1057](https://github.com/rollup/rollup/pull/1057)) +- Fix missing namespace member warnings ([#1045](https://github.com/rollup/rollup/issues/1045)) +- Fix TypeError in arrow function without braces returning a function ([#1062](https://github.com/rollup/rollup/pull/1062)) + +## 0.36.4 + +- Only depend on program-level call expressions ([#977](https://github.com/rollup/rollup/issues/977)) + +## 0.36.3 + +- Add `legacy` option for IE8 support ([#989](https://github.com/rollup/rollup/pull/989)) + +## 0.36.2 + +- Insert semicolons where necessary to fix broken code ([#1004](https://github.com/rollup/rollup/issues/1004)) +- Include module ID and location when warning about top-level `this` ([#1012](https://github.com/rollup/rollup/pull/1012)) +- More informative error for missing exports ([#1033](https://github.com/rollup/rollup/issues/1033)) +- `options.moduleContext` for per-module context overrides ([#1023](https://github.com/rollup/rollup/pull/1023)) + +## 0.36.1 + +- Include naked block statements ([#981](https://github.com/rollup/rollup/issues/981)) +- Correctly include falsy alternate statements in optimised if blocks ([#973](https://github.com/rollup/rollup/issues/973)) +- Prevent omission of default exports that are only used by the exporting module ([#967](https://github.com/rollup/rollup/pull/967)) +- Prevent warning on `auto` exports with ES output ([#966](https://github.com/rollup/rollup/pull/966)) + +## 0.36.0 + +- `export { foo as default }` no longer creates a live binding ([#860](https://github.com/rollup/rollup/issues/860)) + +## 0.35.15 + +- Warn on missing unused imports in deshadowing phase ([#928](https://github.com/rollup/rollup/issues/928)) +- Always add a newline to the end of bundles ([#958](https://github.com/rollup/rollup/issues/958)) + +## 0.35.14 + +- Include all parent statements of expression with effects, up to function boundary ([#930](https://github.com/rollup/rollup/issues/930)) + +## 0.35.13 + +- Include superclasses when including their subclasses ([#932](https://github.com/rollup/rollup/issues/932)) + +## 0.35.12 + +- Add `interop: false` option to disable unwrapping of external imports ([#939](https://github.com/rollup/rollup/issues/939)) + +## 0.35.11 + +- Deconflict reified namespaces with other declarations ([#910](https://github.com/rollup/rollup/issues/910)) + +## 0.35.10 + +- Only remove EmptyStatement nodes directly inside blocks ([#913](https://github.com/rollup/rollup/issues/931)) + +## 0.35.9 + +- Support Node 0.12 ([#909](https://github.com/rollup/rollup/issues/909)) + +## 0.35.8 + +- Correctly deshadow re-assigned module functions ([#910](https://github.com/rollup/rollup/issues/910)) + +## 0.35.7 + +- Refactor `flushTime.js` ([#922](https://github.com/rollup/rollup/pull/922)) + +## 0.35.6 + +- Fix browser build + +## 0.35.5 + +- Allow empty for loop heads ([#919](https://github.com/rollup/rollup/issues/919)) + +## 0.35.4 + +- Preserve effects in for-of and for-in loops ([#870](https://github.com/rollup/rollup/issues/870)) +- Remove empty statements ([#918](https://github.com/rollup/rollup/pull/918)) + +## 0.35.3 + +- Render identifiers inside template literals + +## 0.35.2 + +- Fix broken build caused by out of date locally installed dependencies + +## 0.35.1 + +- Rewrite deconflicted class identifiers ([#915](https://github.com/rollup/rollup/pull/915)) +- Include `dependencies` in `bundle.modules` objects ([#903](https://github.com/rollup/rollup/issues/903)) +- Update to Acorn 4 ([#914](https://github.com/rollup/rollup/pull/914)) + +## 0.35.0 + +- Rewrite analysis/tree-shaking code ([#902](https://github.com/rollup/rollup/pull/902)) +- Include conditional mutations of global objects ([#901](https://github.com/rollup/rollup/issues/901)) +- Only reify namespaces if necessary ([#898](https://github.com/rollup/rollup/issues/898)) +- Track mutations of aliased globals ([#893](https://github.com/rollup/rollup/issues/893)) +- Include duplicated var declarations ([#716](https://github.com/rollup/rollup/issues/716)) + +## 0.34.13 + +- Pass `{ format }` through to `transformBundle` ([#867](https://github.com/rollup/rollup/issues/867)) + +## 0.34.12 + +- Fix `rollup --watch` ([#887](https://github.com/rollup/rollup/issues/887)) +- Case-sensitive paths ([#862](https://github.com/rollup/rollup/issues/862)) + +## 0.34.11 + +- Prevent leaky state when `bundle` is reused ([#875](https://github.com/rollup/rollup/issues/875)) +- Ensure `intro` appears before interop block ([#880](https://github.com/rollup/rollup/issues/880)) + +## 0.34.10 + +- Allow custom `options.context` to replace top-level `this` ([#851](https://github.com/rollup/rollup/issues/851)) +- Fix `noConflict` when used via `rollup --config` ([#846](https://github.com/rollup/rollup/issues/846)) +- Place `outro` block _after_ export block ([#852](https://github.com/rollup/rollup/issues/852)) + +## 0.34.9 + +- Disable indentation by default, for faster bundle generation ([#812](https://github.com/rollup/rollup/pull/812)) +- More helpful error on missing entry file ([#802](https://github.com/rollup/rollup/issues/802)) +- Preserve comments before import declarations ([#815](https://github.com/rollup/rollup/pull/815)) + +## 0.34.8 + +- Wrap UMD factory function in parens to avoid lazy parsing ([#774](https://github.com/rollup/rollup/pull/774)) + +## 0.34.7 + +- Leave it up to resolveId to normalize the entry path ([#835](https://github.com/rollup/rollup/pull/835)) +- Cache decoded mappings ([#834](https://github.com/rollup/rollup/pull/834)) + +## 0.34.5 + +- Fix circular export ([#813](https://github.com/rollup/rollup/issues/813)) + +## 0.34.4 + +- Module render performance tweak ([#823](https://github.com/rollup/rollup/pull/823)) + +## 0.34.3 + +- Avoid infinite recursion in `Bundle.sort()` ([#800](https://github.com/rollup/rollup/pull/800)) + +## 0.34.2 + +- resolveId calls are cached now to improve incremental build +- Fixed error message recursion in plugins + +## 0.34.1 + +- Support `paths` config ([#754](https://github.com/rollup/rollup/issues/754)) +- Allow `export *` from external module, internally + +## 0.34.0 + +- Use resolved IDs for relative imports that are also external modules, to allow `options.globals` to work with them ([#763](https://github.com/rollup/rollup/issues/763)) +- Ensure reassigned exports are declared in an ES bundle, and remove empty `exports.foo;` statements ([#755](https://github.com/rollup/rollup/issues/755)) +- Add newline after sourcemap comment ([#756](https://github.com/rollup/rollup/issues/756)) + +## 0.33.2 + +- Add `bundle` as second argument to `ongenerate` and `onwrite` hooks ([#773](https://github.com/rollup/rollup/pull/773)) +- Warn on top-level `this` ([#770](https://github.com/rollup/rollup/issues/770)) + +## 0.33.1 + +- Fix `--no-strict` option ([#751](https://github.com/rollup/rollup/pull/751)) +- Fix Windows edge case with case-sensitive paths ([#760](https://github.com/rollup/rollup/pull/760)) + +## 0.33.0 + +- Downgrade missing transformer sourcemap to a warning, not an error, and print the name of the offending plugin if possible ([#746](https://github.com/rollup/rollup/issues/746)) +- Warn if same name is re-exported from two modules ([#722](https://github.com/rollup/rollup/issues/722)) + +## 0.32.4 + +- Add `ongenerate` and `onwrite` plugin hooks ([#742](https://github.com/rollup/rollup/pull/742)) + +## 0.32.3 + +- Generated correct sourcemaps with reified namespaces ([#668](https://github.com/rollup/rollup/issues/668)) +- Exclude plugin helper modules from sourcemaps ([#747](https://github.com/rollup/rollup/pull/747)) + +## 0.32.2 + +- Allow `--globals` to work with `--external` or `options.external` in whatever configuration ([#743](https://github.com/rollup/rollup/issues/743)) + +## 0.32.1 + +- Preserve side-effects to default exports that coincide with used named exports ([#733](https://github.com/rollup/rollup/issues/733)) +- Support `rollup -c node:pkgname` ([#736](https://github.com/rollup/rollup/issues/736)) + +## 0.32.0 + +- Deprecate `es6` format in favour of `es` ([#468](https://github.com/rollup/rollup/issues/468)) +- Add correct `jsnext:main` build ([#726](https://github.com/rollup/rollup/pull/726)) + +## 0.31.2 + +- Allow `load` plugins to provide sourcemap ([#715](https://github.com/rollup/rollup/pull/715)) +- Allow `sourceMapFile` in config options ([#717](https://github.com/rollup/rollup/issues/717)) + +## 0.31.1 + +- Logging for errors emitted by `rollup-watch` ([#712](https://github.com/rollup/rollup/issues/712)) + +## 0.31.0 + +- Rewrite top-level `this` as `undefined` ([#707](https://github.com/rollup/rollup/pull/707)) +- Pass `options.acorn` to Acorn ([#564](https://github.com/rollup/rollup/issues/564)) + +## 0.30.0 + +- Bundle CLI ([#700](https://github.com/rollup/rollup/issues/700)) +- Ensure absolute paths are normalised ([#704](https://github.com/rollup/rollup/issues/704)) +- Allow `rollup --watch` to work with targets + +## 0.29.1 + +- Merge `target` options with main options ([#701](https://github.com/rollup/rollup/issues/701)) +- Update magic-string ([#690](https://github.com/rollup/rollup/issues/690)) + +## 0.29.0 + +- `rollup --watch` ([#284](https://github.com/rollup/rollup/issues/284)) + +## 0.28.0 + +- Experimental support for incremental rebuilds ([#658](https://github.com/rollup/rollup/pull/658)) + +## 0.27.1 + +- Ensure names exported from a module are not replaced with reserved words ([#696](https://github.com/rollup/rollup/pull/696)) +- Revert ([#692](https://github.com/rollup/rollup/pull/692)) – resolved IDs must be strings + +## 0.27.0 + +- Use native promises instead of `es6-promise` ([#689](https://github.com/rollup/rollup/issues/689)) +- Support multiple targets in config files ([#655](https://github.com/rollup/rollup/issues/655)) +- Allow `resolveId` plugin functions to return non-strings ([#692](https://github.com/rollup/rollup/pull/692)) + +## 0.26.7 + +- Distinguish between default and namespace imports of external module ([#637](https://github.com/rollup/rollup/issues/637)) +- Add `__esModule` property to named exports in AMD, CJS and UMD modes ([#650](https://github.com/rollup/rollup/issues/650)) + +## 0.26.6 + +- Deconflict named imports from external modules in ES bundles ([#659](https://github.com/rollup/rollup/issues/659)) +- Support `options.preferConst` to generate `const` declarations for exports rather than `var` declarations ([#653](https://github.com/rollup/rollup/issues/653)) + +## 0.26.5 + +- Preserve `debugger` statements ([#664](https://github.com/rollup/rollup/issues/664)) +- Allow `options.external` to be a function ([#522](https://github.com/rollup/rollup/issues/522)) + +## 0.26.4 + +- Prevent plugin-provided external IDs being normalised ([#630](https://github.com/rollup/rollup/issues/630), [#633](https://github.com/rollup/rollup/issues/633)) +- Throw if module exports/re-exports the same name twice, or has multiple default exports ([#679](https://github.com/rollup/rollup/issues/679)) +- Warn about `eval` security issue ([#675](<(https://github.com/rollup/rollup/issues/675)>)) + +## 0.26.3 + +- Ensure reference is not incorrectly marked as a reassignment ([#648](https://github.com/rollup/rollup/issues/648)) + +## 0.26.2 + +- Sanity check output of `load` hook ([#607](https://github.com/rollup/rollup/issues/607)) +- Correct scoping for ID class expressions ([#626](https://github.com/rollup/rollup/issues/626)) +- Warn if named and default exports are used together in auto mode ([#587](https://github.com/rollup/rollup/issues/587)) +- Allow variable initialisers to be rewritten if necessary ([#632](https://github.com/rollup/rollup/issues/632)) +- Prevent double `var` with no-treeshake option ([#639](https://github.com/rollup/rollup/pull/639)) + +## 0.26.1 + +- Add `treeshake: false`/`--no-treeshake` option for debugging ([#505](https://github.com/rollup/rollup/issues/505)) +- Update build process to use Bublé ([#620](https://github.com/rollup/rollup/pull/620)) + +## 0.26.0 + +- Add `noConflict`/`--no-conflict` option for UMD builds ([#580](https://github.com/rollup/rollup/pull/580)) +- Normalise relative external paths ([#591](https://github.com/rollup/rollup/pull/591)) +- Report files causing transform errors ([#609](https://github.com/rollup/rollup/pull/609)) +- Handle sourcemap segments with a single member ([#619](https://github.com/rollup/rollup/pull/619)) +- Update dependencies + +## 0.25.8 + +- Unixize entry path ([#586](https://github.com/rollup/rollup/pull/586)) + +## 0.25.7 + +- Expand deshadowed shorthand properties ([#575](https://github.com/rollup/rollup/issues/575)) +- Allow external files to be non-existent ([#532](https://github.com/rollup/rollup/issues/532)) + +## 0.25.6 + +- Fix a regression introduced by #566 ([#569](https://github.com/rollup/rollup/issues/569)) +- Prune dead conditional expressions more carefully ([#567](https://github.com/rollup/rollup/issues/567)) + +## 0.25.5 + +- Make sure shorthand destructuring assignments don't break ([#528](https://github.com/rollup/rollup/issues/528)) +- Allow 'exports' key ([#542](https://github.com/rollup/rollup/issues/542)) +- Ensure `foo. bar` where `foo` is a namespace import is rewritten correctly ([#566](https://github.com/rollup/rollup/issues/566)) +- Fix an edge case for exported globals (e.g. `export { document }`) ([#562](https://github.com/rollup/rollup/issues/562)) + +## 0.25.4 + +- Fix misnamed exports of default imports in ES bundles ([#513](https://github.com/rollup/rollup/issues/513)) +- CLI: warn on missing config ([#515](https://github.com/rollup/rollup/pull/515)) +- Detect side-effects in non-top-level member expression assignment ([#476](https://github.com/rollup/rollup/issues/476)) +- Don't remove computed property class keys ([#504](https://github.com/rollup/rollup/issues/504)) +- Augment existing global object rather than replacing ([#493](https://github.com/rollup/rollup/issues/493)) +- Don't fail on `export {}`, warn instead ([#486](https://github.com/rollup/rollup/issues/486)) + +## 0.25.3 + +- Handle non-objects and `null` in `_interopDefault` ([#474](https://github.com/rollup/rollup/issues/474)) + +## 0.25.2 + +- Skip dead branches of a conditional expression (#[465](https://github.com/rollup/rollup/pull/465)) +- Allow globals to be exported ([#472](https://github.com/rollup/rollup/pull/472)) +- Ensure reassigned exports are exported ([#484](https://github.com/rollup/rollup/issues/484)) + +## 0.25.1 + +- Throw error if namespace is called ([#446](https://github.com/rollup/rollup/issues/446)) +- Prevent shadowing bug in ES6 output ([#441](https://github.com/rollup/rollup/pull/441)) +- Prevent `var exports.foo` ([#426](https://github.com/rollup/rollup/issues/426)) +- Prevent double export of aliased symbols ([#438](https://github.com/rollup/rollup/issues/438)) +- Provide more informative error if Rollup is used in-browser without appropriate `resolveId`/`load` hooks ([#275](https://github.com/rollup/rollup/issues/275)) +- Use `_interopDefault` function to DRY out code with many external dependencies, in CommonJS output ([#458](https://github.com/rollup/rollup/pull/458)) + +## 0.25.0 + +- **breaking** Module order is determined according to spec, rather than in a way designed to prevent runtime errors. Rollup will warn if it detects runtime errors are likely ([#435](https://github.com/rollup/rollup/issues/435)) +- Prevent overly aggressive tree-shaking with complex call expressions ([#440](https://github.com/rollup/rollup/issues/440)) + +## 0.24.1 + +- Handle calls to default exports other that are not function expressions or references to function declarations ([#421](https://github.com/rollup/rollup/issues/421)) +- Ensure namespace blocks are created for chained imports ([#430](https://github.com/rollup/rollup/issues/430)) +- Include references in computed property keys ([#434](https://github.com/rollup/rollup/issues/434)) +- Use CLI `--external` option correctly ([#417](https://github.com/rollup/rollup/pull/417)) +- Allow relative imports to be treated as external, if absolute paths are provided in `options.external` ([#410](https://github.com/rollup/rollup/issues/410)) +- Make IIFE output adhere to Crockford style ([#415](https://github.com/rollup/rollup/pull/415)) + +## 0.24.0 + +- No longer attempts to resolve IDs in `options.external` ([#407](https://github.com/rollup/rollup/issues/407)) +- Fix broken sourcemap resolution in cases where some modules are transformed and others aren't ([#404](https://github.com/rollup/rollup/issues/404)) + +## 0.23.2 + +- Ensure `dest` or `sourceMapFile` is resolved against CWD for purposes of sourcemap generation ([#344](https://github.com/rollup/rollup/issues/344)) +- Support `banner`, `footer`, `intro` and `outro` options via CLI ([#330](https://github.com/rollup/rollup/issues/330)) +- Allow `options.global` to be a function rather than an object, and warn on missing names ([#293](https://github.com/rollup/rollup/issues/293)) +- Ensure side-effects are captured in cyclical call expressions ([#397](https://github.com/rollup/rollup/issues/397)) +- Fix parse error with body-less arrow function expressions ([#403](https://github.com/rollup/rollup/issues/403)) + +## 0.23.1 + +- Reinstate missing fix from ([#392](https://github.com/rollup/rollup/pull/392)) + +## 0.23.0 + +- Add `bundleTransform` plugin hook and option ([#387](https://github.com/rollup/rollup/pull/387)) +- Correctly store names in sourcemaps, regardless of transformers +- Add `--environment` option to CLI ([#388](https://github.com/rollup/rollup/pull/388)) +- Handle destructuring in exports ([#374](https://github.com/rollup/rollup/issues/374)) +- Fix UMD global exports bug introduced in 0.22.1 ([#392](https://github.com/rollup/rollup/pull/392)) + +## 0.22.2 + +- Prevent lost `var` keywords ([#390](https://github.com/rollup/rollup/issues/390)) + +## 0.22.1 + +- Update expected option keys ([#379](https://github.com/rollup/rollup/issues/379)) +- Handle transformers that return stringified sourcemaps ([#377](https://github.com/rollup/rollup/issues/377)) +- Automatically create missing namespaces if `moduleName` contains dots ([#378](https://github.com/rollup/rollup/issues/378)) +- Ignore external dependency warnings coming from config file ([#333](https://github.com/rollup/rollup/issues/333)) +- Update to latest magic-string for performance boost + +## 0.22.0 + +- Duplicate warnings are squelched ([#362](https://github.com/rollup/rollup/issues/362)) +- Plugins can manipulate or override the `options` object ([#371](https://github.com/rollup/rollup/pull/371)) + +## 0.21.3 + +- Validate option keys ([#348](https://github.com/rollup/rollup/pull/348)) +- Allow namespaces imports to sit alongside named imports ([#355](https://github.com/rollup/rollup/issues/355)) +- Count references inside destructured objects ([#364](https://github.com/rollup/rollup/issues/364)) +- Preserve top-level `delete` statements ([#352](https://github.com/rollup/rollup/issues/352)) + +## 0.21.2 + +- Missing relative imports are an error, not a warning ([#321](https://github.com/rollup/rollup/issues/321)) +- Fixed incorrectly renamed default exports in ES6 bundles ([#339](https://github.com/rollup/rollup/issues/339)) +- Fixed infinite recursion bug ([#341](https://github.com/rollup/rollup/issues/341)) + +## 0.21.1 + +- Remove `aggressive: true` (was too aggressive) ([#309](https://github.com/rollup/rollup/pull/309)) +- Handle top-level block statements ([#326](https://github.com/rollup/rollup/issues/326)) +- Optimise namespaces with default exports ([#314](https://github.com/rollup/rollup/issues/314)) + +## 0.21.0 + +- Only include statements whose side-effects are relevant (i.e. contribute to exports or affect global state) ([#253](https://github.com/rollup/rollup/pull/253)) ([#253](https://github.com/rollup/rollup/pull/253)) +- Exclude dead branches from analysis and inclusion ([#249](https://github.com/rollup/rollup/pull/249)) +- Add `aggressive: true` option to eliminate all side-effects outside entry module +- More informative error when re-exporting non-existent binding ([#274](https://github.com/rollup/rollup/issues/274)) +- Fix infinite recursion bug ([#291](https://github.com/rollup/rollup/issues/291)) +- Log errors when using `rollup --config` ([#288](https://github.com/rollup/rollup/pull/288)) +- Return rejected promises on startup instead of throwing error, if options are invalid ([#303](https://github.com/rollup/rollup/pull/303)) + +## 0.20.5 + +- Ensure re-exports don't create a local binding ([#270](https://github.com/rollup/rollup/pull/270)) + +## 0.20.4 + +- Check file exists at resolve time, to allow filenames with non-extension dots in them ([#250](https://github.com/rollup/rollup/pull/250)) +- Import `Promise` where used, for Node 0.10 support ([#254](https://github.com/rollup/rollup/issues/254)) +- Allow asynchronous transformer plugins ([#260](https://github.com/rollup/rollup/issues/260)) +- Don't assume re-exported bindings are globals when deconflicting ([#267](https://github.com/rollup/rollup/issues/267)) + +## 0.20.3 + +- Fix bug where multiple `export *` declarations caused error ([#244](https://github.com/rollup/rollup/pulls/244)) +- Missing namespace exports are a warning, not an error ([#244](https://github.com/rollup/rollup/pulls/244)) +- Plugins can provide `banner` and `footer` options (string, or function that returns a string) ([#235](https://github.com/rollup/rollup/issues/235)) +- Warn on encountering `eval` ([#186](https://github.com/rollup/rollup/issues/186)) + +## 0.20.2 + +- Handle errors in build config file +- More robust deconflicting, in cases where e.g. `foo$1` already exists +- Use Rollup CLI for own build process + +## 0.20.1 + +- Support `--config` file to enable plugins with CLI ([#226](https://github.com/rollup/rollup/pulls/226)) +- Prevent `default` being used as variable name ([#215](https://github.com/rollup/rollup/issues/215)) +- Update deps + +## 0.20.0 + +- Support for [plugins](https://github.com/rollup/rollup/wiki/Plugins) ([#207](https://github.com/rollup/rollup/pulls/207)) +- BREAKING – `options.transform`, `options.load`, `options.resolveId`, `options.resolveExternal` and `options.external` are no longer supported, and should be handled by plugins. [More info](https://github.com/rollup/rollup/wiki/Plugins) +- BREAKING – the .js extension is only added if it looks like there's no extension, allowing e.g. `import data from 'data.json'` (with the appropriate transformer). For safety, always include the file extension – import `./foo.js`, not `./foo` + +## 0.19.2 + +- Fix exporting namespaces to include all of their exports ([#204](https://github.com/rollup/rollup/issues/204)) +- Namespace exotic objects are frozen to ensure that its properties cannot be modified, reconfigured, redefined or deleted ([#203](https://github.com/rollup/rollup/pulls/203)) +- Fix `ReferenceError: Promise is not defined` in node v0.10 ([#189](https://github.com/rollup/rollup/issues/189)) + +## 0.19.1 + +- Fix `module.basename()` when used with custom `resolveId` function +- Use [rollup-babel](https://github.com/rollup/rollup-babel) to build self +- Exposed the version string through the API: `require( 'rollup' ).VERSION` + +## 0.19.0 + +- **breaking** The `transform` option is no longer passed through to custom loaders. Loaders should only concern themselves with providing source code; transformation will _always_ take place +- `options.transform` functions can return a string, or a `{code, map, ast}` object. Where possible, sourcemap chains will be flattened ([#175](https://github.com/rollup/rollup/pull/175)) +- `options.resolveId`, `options.resolveExternal` and `options.load` can each be a function or an array of functions. If an array, the first non-null/undefined return value is used. In both cases, failed resolution/loading will fall back to the defaults, unless an error is thrown. ([#174](https://github.com/rollup/rollup/pull/174)) +- New `intro` and `outro` options – similar to `banner` and `footer` except inserted _inside_ any format-specific wrapper +- Multiple var declarations in an export block (e.g. `export let a = 1, b = 2`) are split up to facilitate tree-shaking ([#171](https://github.com/rollup/rollup/issues/171)) +- More informative error when using a missing namespace property ([#169](https://github.com/rollup/rollup/pull/169)) +- Update various dependencies + +## 0.18.5 + +- Allow namespaces to be assigned to variables ([#168](https://github.com/rollup/rollup/issues/168)) +- Promote `chalk` and `source-map-support` to `dependencies`, as they're used by the CLI ([#167](https://github.com/rollup/rollup/pull/167)) + +## 0.18.4 + +- Make external modules configurable (i.e. `external.config.foo = 'bar'`) without erroring + +## 0.18.3 + +- Crop indent exclusion ranges to exclude enclosing quotes ([#166](https://github.com/rollup/rollup/issues/166)) + +## 0.18.2 + +- Include definitions of namespace members that are exported as defaults + +## 0.18.1 + +- Include `acorn.parse` in bundle, remove `sander` from dependencies, simplify build + +## 0.18.0 + +- Internal rewrite +- Reinstate statically-analysable namespace imports +- Avoid using getters in namespace blocks where possible ([#144](https://github.com/rollup/rollup/issues/144)) +- Track variable aliases ([#96](https://github.com/rollup/rollup/issues/96)) +- Prevent multiline strings being indented ([#164](https://github.com/rollup/rollup/issues/164)) + +## 0.17.4 + +- Allow imports from hidden directories (replay of [#133](https://github.com/rollup/rollup/issues/133)) + +## 0.17.3 + +- Handle parenthesised default exports ([#136](https://github.com/rollup/rollup/issues/136)) + +## 0.17.2 + +- Allow use of scoped npm packages ([#131](https://github.com/rollup/rollup/issues/131)) + +## 0.17.1 + +- Allow namespaces to be passed to a function ([#149](https://github.com/rollup/rollup/issues/149)) + +## 0.17.0 + +- Roll back to 0.15.0 and reapply subsequent fixes pending resolution of ([#132](https://github.com/rollup/rollup/issues/132)) and related issues + +## 0.16.4 + +- Fix import paths with `.` ([#133](https://github.com/rollup/rollup/issues/133)) +- Prevent sourceMappingURL confusion leading to broken sourcemap +- Add code coverage reporting [#130](https://github.com/rollup/rollup/pull/130)) +- Add `modules` property to user-facing `bundle` – an array with `{id}` objects ([#128](https://github.com/rollup/rollup/issues/128)) + +## 0.16.3 + +- Prevent adjacent blocks of multiple var declarations causing magic-string failure ([#105](https://github.com/rollup/rollup/issues/105)) + +## 0.16.2 + +- Top-level function calls and assignments to globals are treated as side-effects, and always included +- Import files from subdirectories of external packages, e.g. `import mod from 'foo/sub/mod'` ([#126](https://github.com/rollup/rollup/issues/126)) + +## 0.16.1 + +- Handle assignment patterns, and destructured/rest parameters, when analysing scopes +- Fix bug preventing project from self-building (make base `Identifier` class markable) + +## 0.16.0 + +- Internal refactoring ([#99](https://github.com/rollup/rollup/pull/99)) +- Optimisation for statically-analysable namespace imports ([#99](https://github.com/rollup/rollup/pull/99)) +- Windows support (theoretically!) ([#117](https://github.com/rollup/rollup/pull/117) / [#119](https://github.com/rollup/rollup/pull/119)) + +## 0.15.0 + +- Load all modules specified by `import` statements, and do tree-shaking synchronously once loading is complete. This results in simpler and faster code, and enables future improvements ([#97](https://github.com/rollup/rollup/pull/97)) +- Only rewrite `foo` as `exports.foo` when it makes sense to ([#92](https://github.com/rollup/rollup/issues/92)) +- Fix bug with shadowed variables that are eventually exported ([#91](https://github.com/rollup/rollup/issues/91)) +- Exclude unused function declarations that happen to modify a used name ([#90](https://github.com/rollup/rollup/pull/90)) +- Simplify internal `Scope` model – scopes always attach to blocks, never function expressions/declarations + +## 0.14.1 + +- `export { name } from './other'` does not create a local binding ([#16](https://github.com/rollup/rollup/issues/16)) +- A single binding can be exported under multiple names ([#18](https://github.com/rollup/rollup/issues/18)) +- `useStrict` option exposed to CLI as `--strict`/`--no-strict` ([#81](https://github.com/rollup/rollup/issues/81)) +- Neater exports from ES6 bundles + +## 0.14.0 + +- Internal refactoring +- Correctly deconflict generated default export names ([#72](https://github.com/rollup/rollup/issues/72)) +- Handle `export { x } from 'y'` declarations ([#74](https://github.com/rollup/rollup/issues/74)) +- Dedupe named imports from external modules in ES6 bundles ([#77](https://github.com/rollup/rollup/issues/77)) + +## 0.13.0 + +- Support `banner` and `footer` options ([#66](https://github.com/rollup/rollup/pull/66)) +- Remove pre-existing sourcemap comments ([#66](https://github.com/rollup/rollup/pull/66)) +- Deconflict external imports ([#66](https://github.com/rollup/rollup/pull/66)) +- Use existing AST, if provided ([#66](https://github.com/rollup/rollup/pull/66)) +- Rename internal namespace exports as appropriate ([#66](https://github.com/rollup/rollup/pull/66)) +- Remove uninitialised var declarations that get exported ([#66](https://github.com/rollup/rollup/pull/66)) +- Rename variables named `exports` to avoid conflicts ([#66](https://github.com/rollup/rollup/pull/66)) + +## 0.12.1 + +- Don't attempt to mark statements belonging to external modules ([#68](https://github.com/rollup/rollup/issues/68)) +- Correctly deshadow variables that conflict with imports ([#68](https://github.com/rollup/rollup/issues/68)) + +## 0.12.0 + +- Internal re-architecting, resulting in more efficient bundling with reduced memory usage +- Shorthand properties are expanded if necessary ([#61](https://github.com/rollup/rollup/issues/61)) +- Fixed various bugs with bundle external dependencies, particularly when generating ES6 bundles ([#59](https://github.com/rollup/rollup/issues/59)) +- Add `--globals` option to CLI ([#60](https://github.com/rollup/rollup/pull/60)) +- Allow imports of external modules for side-effects ([#55](https://github.com/rollup/rollup/pull/55)) +- Prevent Rollup hanging on non-existent external module ([#54](https://github.com/rollup/rollup/pull/54)) + +## 0.11.4 + +- Side-effect preservation applies to internal default exports ([#43](https://github.com/rollup/rollup/issues/43)) + +## 0.11.3 + +- Class methods are not incorrectly renamed ([#42](https://github.com/rollup/rollup/issues/42)) +- External modules are assigned names before canonical names are determined ([#42](https://github.com/rollup/rollup/issues/42)) + +## 0.11.2 + +- Correctly handle computed properties (e.g. `foo[bar]`) when discovering dependencies ([#47](https://github.com/rollup/rollup/pull/47)) + +## 0.11.1 + +- Support for `export * from '..'` ([#46](https://github.com/rollup/rollup/pull/46)) + +## 0.11.0 + +- Experimental browser-friendly build (`dist/rollup.browser.js`) ([#25](https://github.com/rollup/rollup/issues/25)) +- Internal re-architecting to make discovery process simpler and more performant +- Preservation of side-effects that happen in a separate module to the affected definition ([#39](https://github.com/rollup/rollup/issues/39)) + +## 0.10.0 + +- Better sorting algorithm – sorting happens at the module level, rather than the statement level. This avoids certain edge cases +- IIFEs are ignored for the purposes of distinguishing between 'strong' and 'weak' dependencies +- Empty `var` declarations for exported bindings are omitted + +## 0.9.1 + +- Much faster statement insertion (fixes major 0.9.0 performance regression) + +## 0.9.0 + +- BREAKING - `resolvePath` is now `resolveId`. The returned `id` (which by default is a filepath) is passed to the `load` function, which can optionally be overridden, and which is applied to all modules including the entry module. This allows custom resolver and loading logic for integration with third party systems (e.g. JSPM) or, eventually, in-browser usage ([#30](https://github.com/rollup/rollup/issues/30)) +- A statement cannot appear after later statements from the same bundle ([#34](https://github.com/rollup/rollup/issues/34)) +- Tricky cyclical dependencies are handled ([#36](https://github.com/rollup/rollup/issues/36)) +- `sourcemap` option is used by CLI (was omitted previously) + +## 0.8.3 + +- Correctly rename functions that have arguments with the same name ([#32](https://github.com/rollup/rollup/issues/32)) +- Ensure unused default exports are given a legal name ([#33](https://github.com/rollup/rollup/issues/33)) + +## 0.8.2 + +- Support `moduleId` and `moduleName` via CLI ([#24](https://github.com/rollup/rollup/issues/24)) + +## 0.8.1 + +- Anonymous functions that are exported as default are converted to named function declarations for correct hoisting, rather than being bound to functions ([#29](https://github.com/rollup/rollup/issues/29)) +- Automatically-generated default export names are deconflicted with local definitions ([#29](https://github.com/rollup/rollup/issues/29)) + +## 0.8.0 + +- Top-level variable declarations with multiple declarators are split up, to avoid unnecessary code importing and incorrectly-ordered statements ([#26](https://github.com/rollup/rollup/issues/26)) +- `this` at the top level is `undefined` ([#28](https://github.com/rollup/rollup/issues/28)) + +## 0.7.8 + +- Avoid using `path.parse` - unsupported in node 0.10 + +## 0.7.7 + +- Promise `source-map-support` from `devDependencies` to `dependencies` ([#23](https://github.com/rollup/rollup/issues/23)) + +## 0.7.6 + +- Better placement of `export default` statements ([#21](https://github.com/rollup/rollup/issues/21)) +- Prevent function calls and property assignments from being treated as rebinding for sake of unbound default exports +- Add `--external foo,bar,baz` option to CLI (equivalent to `external: ['foo', 'bar', 'baz']`) +- Add CLI tests + +## 0.7.5 + +- Prevent accidental conflicts with the global namespace ([#20](https://github.com/rollup/rollup/issues/20)) + +## 0.7.4 + +- More precise statement re-ordering to satisfy `export default` constraint (fixes bug introduced in 0.7.3) + +## 0.7.3 + +- Default exports are not bound. To enable this, statements within a module are sorted to retain their original order ([#15](https://github.com/rollup/rollup/issues/15)) +- Better positioning of comments ([#14](https://github.com/rollup/rollup/issues/14)) +- Various fixes to get Travis-CI rigged up + +## 0.7.2 + +- Fix sourcemap paths on Windows ([#6](https://github.com/rollup/rollup/pull/6)) + +## 0.7.1 + +- Named functions can be used as default exports from a bundle +- Method calls are assumed to mutate the owner (i.e. `foo.bar()` mutates `foo`) ([#13](https://github.com/rollup/rollup/issues/13)) +- `options.indent` can be used to control indentation of resulting bundle. `options.true` (default) means 'auto', `options.false` means empty string. Alternatively specify whitespace e.g. `' '` or `'\t'` ([#5](https://github.com/rollup/rollup/issues/5)) + +## 0.7.0 + +- Ensure statements are always separated by a newline ([#9](https://github.com/rollup/rollup/pull/9)) +- Use CommonJS `exports` correctly (UMD exports) +- Throw error if `moduleName` is required but missing (UMD exports) +- Attach IIFE global to `this` rather than `window` +- Allow names inside bundle to the the names of `Object.prototype` properties ([#12](https://github.com/rollup/rollup/pull/12)) +- Keep exports live ([#11](https://github.com/rollup/rollup/pull/11)) + +## 0.6.5 + +- Add sourceMappingURL comment to code, as appropriate +- Higher resolution sourcemaps + +## 0.6.4 + +- Fix CJS bundling with default export + +## 0.6.3 + +- Fix exports and external module imports with some output formats +- Fix endless cycle bug on Windows ([#3](https://github.com/rollup/rollup/pull/3)) - thanks @Bobris + +## 0.6.2 + +- Permit assignments to properties of imported bindings + +## 0.6.1 + +- Support for basic transformers + +## 0.6.0 + +- BREAKING - `rollup.rollup` and `bundle.write` both take a single options argument +- BREAKING - external modules must be declared upfront with `options.external: [...]` +- Non-relative module paths will be resolved by looking for `jsnext:main` fields in the appropriate `package.json` files. This behaviour can be overridden by passing an alternative `resolveExternal` function +- Fix sourcemap options +- Include CLI files in npm package (duh) + +## 0.5.0 + +- Command line interface +- Sourcemap generation +- Correct behaviour with `export { x as y } from 'z'` + +## 0.4.1 + +- More import name deconflicting + +## 0.4.0 + +- Self-hosting! `rollup.rollup` now rolls up rollup +- Fix bug with comments inside a statement later being appended to it +- Prevent shadowing of external modules +- Rewrite computed property identifiers where necessary +- Preserve original statement order where possible +- Internal refactoring + +## 0.3.1 + +- Saner deconflicting +- Rename namespace imports from external modules correctly + +## 0.3.0 + +- Basic functionality present, mostly spec-compliant + +## 0.2.1 + +- Include dist files in npm package (duh) + +## 0.2.0 + +- First release capable of doing anything useful +- Still lots of basic functionality missing + +## 0.1.0 + +- Initial experiment diff --git a/node_modules/rollup/LICENSE.md b/node_modules/rollup/LICENSE.md new file mode 100644 index 0000000..d5a5c4f --- /dev/null +++ b/node_modules/rollup/LICENSE.md @@ -0,0 +1,703 @@ +# Rollup core license +Rollup is released under the MIT license: + +The MIT License (MIT) + +Copyright (c) 2017 [these people](https://github.com/rollup/rollup/graphs/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. + +# Licenses of bundled dependencies +The published Rollup artifact additionally contains code with the following licenses: +MIT, ISC + +# Bundled dependencies: +## @rollup/pluginutils +License: MIT +By: Rich Harris +Repository: rollup/plugins + +--------------------------------------- + +## acorn +License: MIT +By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine +Repository: https://github.com/acornjs/acorn.git + +> MIT License +> +> Copyright (C) 2012-2022 by various contributors (see AUTHORS) +> +> 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. + +--------------------------------------- + +## acorn-walk +License: MIT +By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine +Repository: https://github.com/acornjs/acorn.git + +> MIT License +> +> Copyright (C) 2012-2020 by various contributors (see AUTHORS) +> +> 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. + +--------------------------------------- + +## anymatch +License: ISC +By: Elan Shanker +Repository: https://github.com/micromatch/anymatch + +> The ISC License +> +> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) +> +> 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. + +--------------------------------------- + +## binary-extensions +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/binary-extensions + +> 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. + +--------------------------------------- + +## braces +License: MIT +By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm +Repository: micromatch/braces + +> The MIT License (MIT) +> +> Copyright (c) 2014-2018, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## chokidar +License: MIT +By: Paul Miller, Elan Shanker +Repository: git+https://github.com/paulmillr/chokidar.git + +> 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. + +--------------------------------------- + +## colorette +License: MIT +By: Jorge Bucaran +Repository: jorgebucaran/colorette + +> Copyright © Jorge Bucaran <> +> +> 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. + +--------------------------------------- + +## date-time +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/date-time + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## fill-range +License: MIT +By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling +Repository: jonschlinkert/fill-range + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## glob-parent +License: ISC +By: Gulp Team, Elan Shanker, Blaine Bublitz +Repository: gulpjs/glob-parent + +> The ISC License +> +> Copyright (c) 2015, 2019 Elan Shanker +> +> 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. + +--------------------------------------- + +## hash.js +License: MIT +By: Fedor Indutny +Repository: git@github.com:indutny/hash.js + +--------------------------------------- + +## inherits +License: ISC +Repository: git://github.com/isaacs/inherits + +> The ISC License +> +> Copyright (c) Isaac Z. Schlueter +> +> 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. + +--------------------------------------- + +## is-binary-path +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-binary-path + +> 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. + +--------------------------------------- + +## is-extglob +License: MIT +By: Jon Schlinkert +Repository: jonschlinkert/is-extglob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2016, Jon Schlinkert +> +> 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. + +--------------------------------------- + +## is-glob +License: MIT +By: Jon Schlinkert, Brian Woodward, Daniel Perez +Repository: micromatch/is-glob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2017, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## is-number +License: MIT +By: Jon Schlinkert, Olsten Larck, Rouven Weßling +Repository: jonschlinkert/is-number + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## is-reference +License: MIT +By: Rich Harris +Repository: git+https://github.com/Rich-Harris/is-reference.git + +--------------------------------------- + +## locate-character +License: MIT +By: Rich Harris +Repository: Rich-Harris/locate-character + +--------------------------------------- + +## magic-string +License: MIT +By: Rich Harris +Repository: https://github.com/rich-harris/magic-string + +> Copyright 2018 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. + +--------------------------------------- + +## minimalistic-assert +License: ISC +Repository: https://github.com/calvinmetcalf/minimalistic-assert.git + +> Copyright 2015 Calvin Metcalf +> +> 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. + +--------------------------------------- + +## normalize-path +License: MIT +By: Jon Schlinkert, Blaine Bublitz +Repository: jonschlinkert/normalize-path + +> The MIT License (MIT) +> +> Copyright (c) 2014-2018, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## parse-ms +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/parse-ms + +> 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. + +--------------------------------------- + +## picomatch +License: MIT +By: Jon Schlinkert +Repository: micromatch/picomatch + +> The MIT License (MIT) +> +> Copyright (c) 2017-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## pretty-bytes +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/pretty-bytes + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## pretty-ms +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/pretty-ms + +> 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. + +--------------------------------------- + +## readdirp +License: MIT +By: Thorsten Lorenz, Paul Miller +Repository: git://github.com/paulmillr/readdirp.git + +> 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. + +--------------------------------------- + +## signal-exit +License: ISC +By: Ben Coe +Repository: https://github.com/tapjs/signal-exit.git + +> The ISC License +> +> Copyright (c) 2015, 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. + +--------------------------------------- + +## sourcemap-codec +License: MIT +By: Rich Harris +Repository: https://github.com/Rich-Harris/sourcemap-codec + +> 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. + +--------------------------------------- + +## time-zone +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/time-zone + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## to-regex-range +License: MIT +By: Jon Schlinkert, Rouven Weßling +Repository: micromatch/to-regex-range + +> The MIT License (MIT) +> +> Copyright (c) 2015-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## yargs-parser +License: ISC +By: Ben Coe +Repository: https://github.com/yargs/yargs-parser.git + +> Copyright (c) 2016, 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/rollup/README.md b/node_modules/rollup/README.md new file mode 100644 index 0000000..fb297a9 --- /dev/null +++ b/node_modules/rollup/README.md @@ -0,0 +1,125 @@ +

+ +

+ +

+ + npm version + + + install size + + + code coverage + + + backers + + + sponsors + + + license + + + + Join the chat at https://is.gd/rollup_chat + +

+ +

Rollup

+ +## Overview + +Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the standardized ES module format for code, instead of previous idiosyncratic solutions such as CommonJS and AMD. ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. Rollup can optimize ES modules for faster native loading in modern browsers, or output a legacy module format allowing ES module workflows today. + +## Quick Start Guide + +Install with `npm install --global rollup`. Rollup can be used either through a [command line interface](https://rollupjs.org/#command-line-reference) with an optional configuration file or else through its [JavaScript API](https://rollupjs.org/guide/en/#javascript-api). Run `rollup --help` to see the available options and parameters. The starter project templates, [rollup-starter-lib](https://github.com/rollup/rollup-starter-lib) and [rollup-starter-app](https://github.com/rollup/rollup-starter-app), demonstrate common configuration options, and more detailed instructions are available throughout the [user guide](https://rollupjs.org/). + +### Commands + +These commands assume the entry point to your application is named main.js, and that you'd like all imports compiled into a single file named bundle.js. + +For browsers: + +```bash +# compile to a + +``` + +This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency: + +```html + +``` + +## Options + +This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer: + +```js +require('source-map-support').install({ + handleUncaughtExceptions: false +}); +``` + +This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access. + +```js +require('source-map-support').install({ + retrieveSourceMap: function(source) { + if (source === 'compiled.js') { + return { + url: 'original.js', + map: fs.readFileSync('compiled.js.map', 'utf8') + }; + } + return null; + } +}); +``` + +The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment. +In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'. + +```js +require('source-map-support').install({ + environment: 'node' +}); +``` + +To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps. + + +```js +require('source-map-support').install({ + hookRequire: true +}); +``` + +This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage. + +## Demos + +#### Basic Demo + +original.js: + +```js +throw new Error('test'); // This is the original code +``` + +compiled.js: + +```js +require('source-map-support').install(); + +throw new Error('test'); // This is the compiled code +// The next line defines the sourceMapping. +//# sourceMappingURL=compiled.js.map +``` + +compiled.js.map: + +```json +{ + "version": 3, + "file": "compiled.js", + "sources": ["original.js"], + "names": [], + "mappings": ";;AAAA,MAAM,IAAI" +} +``` + +Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js): + +``` +$ node compiled.js + +original.js:1 +throw new Error('test'); // This is the original code + ^ +Error: test + at Object. (original.js:1:7) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### TypeScript Demo + +demo.ts: + +```typescript +declare function require(name: string); +require('source-map-support').install(); +class Foo { + constructor() { this.bar(); } + bar() { throw new Error('this is a demo'); } +} +new Foo(); +``` + +Compile and run the file using the TypeScript compiler from the terminal: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('source-map-support').install()` in the code base: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node -r source-map-support/register demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### CoffeeScript Demo + +demo.coffee: + +```coffee +require('source-map-support').install() +foo = -> + bar = -> throw new Error 'this is a demo' + bar() +foo() +``` + +Compile and run the file using the CoffeeScript compiler from the terminal: + +```sh +$ npm install source-map-support coffeescript +$ node_modules/.bin/coffee --map --compile demo.coffee +$ node demo.js + +demo.coffee:3 + bar = -> throw new Error 'this is a demo' + ^ +Error: this is a demo + at bar (demo.coffee:3:22) + at foo (demo.coffee:4:3) + at Object. (demo.coffee:5:1) + at Object. (demo.coffee:1:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) +``` + +## Tests + +This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests: + +* Build the tests using `build.js` +* Launch the HTTP server (`npm run serve-tests`) and visit + * http://127.0.0.1:1336/amd-test + * http://127.0.0.1:1336/browser-test + * http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details). +* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/ + +## License + +This code is available under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/node_modules/source-map-support/browser-source-map-support.js b/node_modules/source-map-support/browser-source-map-support.js new file mode 100644 index 0000000..782da50 --- /dev/null +++ b/node_modules/source-map-support/browser-source-map-support.js @@ -0,0 +1,114 @@ +/* + * Support for source maps in V8 stack traces + * https://github.com/evanw/node-source-map-support + */ +/* + The buffer module from node.js, for the browser. + + @author Feross Aboukhadijeh + license MIT +*/ +(this.define||function(R,U){this.sourceMapSupport=U()})("browser-source-map-support",function(R){(function e(C,J,A){function p(f,c){if(!J[f]){if(!C[f]){var l="function"==typeof require&&require;if(!c&&l)return l(f,!0);if(t)return t(f,!0);throw Error("Cannot find module '"+f+"'");}l=J[f]={exports:{}};C[f][0].call(l.exports,function(q){var r=C[f][1][q];return p(r?r:q)},l,l.exports,e,C,J,A)}return J[f].exports}for(var t="function"==typeof require&&require,m=0;mm)return-1;if(58>m)return m-48+52;if(91>m)return m-65;if(123>m)return m-97+26}var t="undefined"!==typeof Uint8Array?Uint8Array:Array;e.toByteArray=function(m){function f(d){q[k++]=d}if(0>16);f((u&65280)>>8);f(u&255)}2===l?(u=p(m.charAt(c))<<2|p(m.charAt(c+1))>>4,f(u&255)):1===l&&(u=p(m.charAt(c))<<10|p(m.charAt(c+1))<<4|p(m.charAt(c+2))>>2,f(u>>8&255),f(u&255));return q};e.fromByteArray=function(m){var f=m.length%3,c="",l;var q=0;for(l=m.length-f;q> +18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);c+=r}switch(f){case 1:r=m[m.length-1];c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<4&63);c+="==";break;case 2:r=(m[m.length-2]<<8)+ +m[m.length-1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),c+="="}return c}})("undefined"===typeof A?this.base64js={}:A)},{}],3:[function(C,J,A){},{}],4:[function(C,J,A){(function(e){var p=Object.prototype.toString,t="function"===typeof e.alloc&&"function"===typeof e.allocUnsafe&&"function"=== +typeof e.from;J.exports=function(m,f,c){if("number"===typeof m)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===p.call(m).slice(8,-1)){f>>>=0;var l=m.byteLength-f;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===c)c=l;else if(c>>>=0,c>l)throw new RangeError("'length' is out of bounds");return t?e.from(m.slice(f,f+c)):new e(new Uint8Array(m.slice(f,f+c)))}if("string"===typeof m){c=f;if("string"!==typeof c||""===c)c="utf8";if(!e.isEncoding(c))throw new TypeError('"encoding" must be a valid string encoding'); +return t?e.from(m,c):new e(m,c)}return t?e.from(m):new e(m)}}).call(this,C("buffer").Buffer)},{buffer:5}],5:[function(C,J,A){function e(a,b,h){if(!(this instanceof e))return new e(a,b,h);var w=typeof a;if("number"===w)var y=0>>0:0;else if("string"===w){if("base64"===b)for(a=(a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")).replace(L,"");0!==a.length%4;)a+="=";y=e.byteLength(a,b)}else if("object"===w&&null!==a)"Buffer"===a.type&&z(a.data)&&(a=a.data),y=0<+a.length?Math.floor(+a.length):0;else throw new TypeError("must start with number, buffer, array or string"); +if(this.length>G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");if(e.TYPED_ARRAY_SUPPORT)var I=e._augment(new Uint8Array(y));else I=this,I.length=y,I._isBuffer=!0;if(e.TYPED_ARRAY_SUPPORT&&"number"===typeof a.byteLength)I._set(a);else{var K=a;if(z(K)||e.isBuffer(K)||K&&"object"===typeof K&&"number"===typeof K.length)if(e.isBuffer(a))for(b=0;ba)throw new RangeError("offset is not uint");if(a+b>h)throw new RangeError("Trying to access beyond buffer length");}function m(a,b,h,w,y,I){if(!e.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>y||ba.length)throw new TypeError("index out of range"); +}function f(a,b,h,w){0>b&&(b=65535+b+1);for(var y=0,I=Math.min(a.length-h,2);y>>8*(w?y:1-y)}function c(a,b,h,w){0>b&&(b=4294967295+b+1);for(var y=0,I=Math.min(a.length-h,4);y>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||ba.length)throw new TypeError("index out of range");}function q(a,b,h,w,y){y||l(a,b,h,4,3.4028234663852886E38,-3.4028234663852886E38);v.write(a,b,h,w,23,4);return h+4}function r(a, +b,h,w,y){y||l(a,b,h,8,1.7976931348623157E308,-1.7976931348623157E308);v.write(a,b,h,w,52,8);return h+8}function k(a){for(var b=[],h=0;h=w)b.push(w);else{var y=h;55296<=w&&57343>=w&&h++;w=encodeURIComponent(a.slice(y,h+1)).substr(1).split("%");for(y=0;y=b.length||y>=a.length);y++)b[y+ +h]=a[y];return y}function g(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}var n=C("base64-js"),v=C("ieee754"),z=C("is-array");A.Buffer=e;A.SlowBuffer=e;A.INSPECT_MAX_BYTES=50;e.poolSize=8192;var G=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(h){return!1}}();e.isBuffer=function(a){return!(null== +a||!a._isBuffer)};e.compare=function(a,b){if(!e.isBuffer(a)||!e.isBuffer(b))throw new TypeError("Arguments must be Buffers");for(var h=a.length,w=b.length,y=0,I=Math.min(h,w);y>>1;break;case "utf8":case "utf-8":h=k(a).length;break;case "base64":h=n.toByteArray(a).length; +break;default:h=a.length}return h};e.prototype.length=void 0;e.prototype.parent=void 0;e.prototype.toString=function(a,b,h){var w=!1;b>>>=0;h=void 0===h||Infinity===h?this.length:h>>>0;a||(a="utf8");0>b&&(b=0);h>this.length&&(h=this.length);if(h<=b)return"";for(;;)switch(a){case "hex":a=b;b=h;h=this.length;if(!a||0>a)a=0;if(!b||0>b||b>h)b=h;w="";for(h=a;hw?"0"+w.toString(16):w.toString(16),w=a+w;return w;case "utf8":case "utf-8":w=a="";for(h=Math.min(this.length,h);b= +this[b]?(a+=g(w)+String.fromCharCode(this[b]),w=""):w+="%"+this[b].toString(16);return a+g(w);case "ascii":return p(this,b,h);case "binary":return p(this,b,h);case "base64":return b=0===b&&h===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(b,h)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,h);h="";for(a=0;ab&&(a+=" ... "));return""};e.prototype.compare=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return e.compare(this,a)};e.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead."); +return this.readUInt8(a)};e.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};e.prototype.write=function(a,b,h,w){if(isFinite(b))isFinite(h)||(w=h,h=void 0);else{var y=w;w=b;b=h;h=y}b=Number(b)||0;y=this.length-b;h?(h=Number(h),h>y&&(h=y)):h=y;w=String(w||"utf8").toLowerCase();switch(w){case "hex":b=Number(b)||0;w=this.length-b;h?(h=Number(h),h>w&&(h=w)):h=w;w=a.length;if(0!==w%2)throw Error("Invalid hex string");h>w/ +2&&(h=w/2);for(w=0;w>8;K%=256;y.push(K);y.push(w)}a=d(y,this,b,h,2);break;default:throw new TypeError("Unknown encoding: "+ +w);}return a};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};e.prototype.slice=function(a,b){var h=this.length;a=~~a;b=void 0===b?h:~~b;0>a?(a+=h,0>a&&(a=0)):a>h&&(a=h);0>b?(b+=h,0>b&&(b=0)):b>h&&(b=h);b>>=0;h||m(this,a,b,1,255,0);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[b]=a;return b+1};e.prototype.writeUInt16LE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeUInt16BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeUInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=a):c(this,a,b,!0);return b+4};e.prototype.writeUInt32BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,127,-128);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[b]=a;return b+1};e.prototype.writeInt16LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeInt16BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):c(this,a,b,!0);return b+4};e.prototype.writeInt32BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);0>a&&(a=4294967295+a+1);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+ +2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeFloatLE=function(a,b,h){return q(this,a,b,!0,h)};e.prototype.writeFloatBE=function(a,b,h){return q(this,a,b,!1,h)};e.prototype.writeDoubleLE=function(a,b,h){return r(this,a,b,!0,h)};e.prototype.writeDoubleBE=function(a,b,h){return r(this,a,b,!1,h)};e.prototype.copy=function(a,b,h,w){h||(h=0);w||0===w||(w=this.length);b||(b=0);if(w!==h&&0!==a.length&&0!==this.length){if(wb||b>=a.length)throw new TypeError("targetStart out of bounds"); +if(0>h||h>=this.length)throw new TypeError("sourceStart out of bounds");if(0>w||w>this.length)throw new TypeError("sourceEnd out of bounds");w>this.length&&(w=this.length);a.length-bw||!e.TYPED_ARRAY_SUPPORT)for(var y=0;yb||b>=this.length)throw new TypeError("start out of bounds"); +if(0>h||h>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;b>1,r=-7;f=t?f-1:0;var k=t?-1:1,u=e[p+f];f+=k;t=u&(1<<-r)-1;u>>=-r;for(r+=c;0>=-r;for(r+=m;0>1,u=23===f?Math.pow(2,-24)-Math.pow(2,-77):0;c=m?0:c-1;var d=m?1:-1,g=0>p||0===p&&0>1/p?1:0;p=Math.abs(p);isNaN(p)||Infinity===p?(p=isNaN(p)?1:0,m=r):(m=Math.floor(Math.log(p)/Math.LN2),1>p*(l=Math.pow(2,-m))&&(m--,l*=2),p=1<=m+k?p+u/l:p+u*Math.pow(2,1-k),2<=p*l&&(m++,l/=2),m+k>=r?(p=0,m=r):1<=m+k?(p=(p*l-1)*Math.pow(2,f),m+=k):(p=p*Math.pow(2,k-1)*Math.pow(2,f),m=0));for(;8<=f;e[t+c]=p&255,c+= +d,p/=256,f-=8);m=m<z?[]:n.slice(v,z-v+1)}c=A.resolve(c).substr(1);l=A.resolve(l).substr(1); +for(var r=q(c.split("/")),k=q(l.split("/")),u=Math.min(r.length,k.length),d=u,g=0;gl&&(l=c.length+l);return c.substr(l,q)}}).call(this,C("g5I+bs"))},{"g5I+bs":9}],9:[function(C,J,A){function e(){}C=J.exports={};C.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(t){return window.setImmediate(t)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var p=[];window.addEventListener("message",function(t){var m=t.source;m!==window&&null!== +m||"process-tick"!==t.data||(t.stopPropagation(),0p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0=f)throw Error("Expected more digits in base 64 VLQ value.");var q=e.decode(p.charCodeAt(t++));if(-1===q)throw Error("Invalid base64 digit: "+p.charAt(t-1));var r=!!(q&32);q&=31;c+=q<>1;m.value=1===(c&1)?-p:p;m.rest=t}},{"./base64":12}],12:[function(C, +J,A){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");A.encode=function(p){if(0<=p&&p=p?p-65:97<=p&&122>=p?p-97+26:48<=p&&57>=p?p-48+52:43==p?62:47==p?63:-1}},{}],13:[function(C,J,A){function e(p,t,m,f,c,l){var q=Math.floor((t-p)/2)+p,r=c(m,f[q],!0);return 0===r?q:0p?-1:p}A.GREATEST_LOWER_BOUND=1;A.LEAST_UPPER_BOUND=2;A.search=function(p,t,m,f){if(0===t.length)return-1;p=e(-1,t.length,p,t,m,f||A.GREATEST_LOWER_BOUND);if(0>p)return-1;for(;0<=p-1&&0===m(t[p],t[p-1],!0);)--p;return p}},{}],14:[function(C,J,A){function e(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var p=C("./util");e.prototype.unsortedForEach=function(t,m){this._array.forEach(t,m)};e.prototype.add=function(t){var m=this._last,f=m.generatedLine, +c=t.generatedLine,l=m.generatedColumn,q=t.generatedColumn;c>f||c==f&&q>=l||0>=p.compareByGeneratedPositionsInflated(m,t)?this._last=t:this._sorted=!1;this._array.push(t)};e.prototype.toArray=function(){this._sorted||(this._array.sort(p.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};A.MappingList=e},{"./util":19}],15:[function(C,J,A){function e(t,m,f){var c=t[m];t[m]=t[f];t[f]=c}function p(t,m,f,c){if(f=m(t[r],q)&&(l+=1,e(t,l,r));e(t,l+1,r);l+=1;p(t,m,f,l-1);p(t,m,l+1,c)}}A.quickSort=function(t,m){p(t,m,0,t.length-1)}},{}],16:[function(C,J,A){function e(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));return null!=d.sections?new m(d,u):new p(d,u)}function p(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version"),n=f.getArg(d,"sources"),v=f.getArg(d,"names",[]),z=f.getArg(d,"sourceRoot",null),G=f.getArg(d,"sourcesContent",null),D=f.getArg(d, +"mappings");d=f.getArg(d,"file",null);if(g!=this._version)throw Error("Unsupported version: "+g);z&&(z=f.normalize(z));n=n.map(String).map(f.normalize).map(function(L){return z&&f.isAbsolute(z)&&f.isAbsolute(L)?f.relative(z,L):L});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(n,!0);this.sourceRoot=z;this.sourcesContent=G;this._mappings=D;this._sourceMapURL=u;this.file=d}function t(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source= +null}function m(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version");d=f.getArg(d,"sections");if(g!=this._version)throw Error("Unsupported version: "+g);this._sources=new l;this._names=new l;var n={line:-1,column:0};this._sections=d.map(function(v){if(v.url)throw Error("Support for url field in sections not implemented.");var z=f.getArg(v,"offset"),G=f.getArg(z,"line"),D=f.getArg(z,"column");if(G=k[d])throw new TypeError("Line must be greater than or equal to 1, got "+ +k[d]);if(0>k[g])throw new TypeError("Column must be greater than or equal to 0, got "+k[g]);return c.search(k,u,n,v)};p.prototype.computeColumnSpans=function(){for(var k=0;k=this._sources.size()&&!this.sourcesContent.some(function(k){return null==k}):!1};p.prototype.sourceContentFor=function(k,u){if(!this.sourcesContent)return null;var d=k;null!=this.sourceRoot&&(d=f.relative(this.sourceRoot,d));if(this._sources.has(d))return this.sourcesContent[this._sources.indexOf(d)]; +var g=this.sources,n;for(n=0;n +g||95!==d.charCodeAt(g-1)||95!==d.charCodeAt(g-2)||111!==d.charCodeAt(g-3)||116!==d.charCodeAt(g-4)||111!==d.charCodeAt(g-5)||114!==d.charCodeAt(g-6)||112!==d.charCodeAt(g-7)||95!==d.charCodeAt(g-8)||95!==d.charCodeAt(g-9))return!1;for(g-=10;0<=g;g--)if(36!==d.charCodeAt(g))return!1;return!0}function r(d,g){return d===g?0:null===d?1:null===g?-1:d>g?1:-1}A.getArg=function(d,g,n){if(g in d)return d[g];if(3===arguments.length)return n;throw Error('"'+g+'" is a required argument.');};var k=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/, +u=/^data:.+,.+$/;A.urlParse=e;A.urlGenerate=p;A.normalize=t;A.join=m;A.isAbsolute=function(d){return"/"===d.charAt(0)||k.test(d)};A.relative=function(d,g){""===d&&(d=".");d=d.replace(/\/$/,"");for(var n=0;0!==g.indexOf(d+"/");){var v=d.lastIndexOf("/");if(0>v)return g;d=d.slice(0,v);if(d.match(/^([^\/]+:\/)?\/*$/))return g;++n}return Array(n+1).join("../")+g.substr(d.length+1)};C=!("__proto__"in Object.create(null));A.toSetString=C?f:c;A.fromSetString=C?f:l;A.compareByOriginalPositions=function(d, +g,n){var v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;if(0!==v||n)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v)return v;v=d.generatedLine-g.generatedLine;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsDeflated=function(d,g,n){var v=d.generatedLine-g.generatedLine;if(0!==v)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v||n)return v;v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine- +g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsInflated=function(d,g){var n=d.generatedLine-g.generatedLine;if(0!==n)return n;n=d.generatedColumn-g.generatedColumn;if(0!==n)return n;n=r(d.source,g.source);if(0!==n)return n;n=d.originalLine-g.originalLine;if(0!==n)return n;n=d.originalColumn-g.originalColumn;return 0!==n?n:r(d.name,g.name)};A.parseSourceMapInput=function(d){return JSON.parse(d.replace(/^\)]}'[^\n]*\n/, +""))};A.computeSourceURL=function(d,g,n){g=g||"";d&&("/"!==d[d.length-1]&&"/"!==g[0]&&(d+="/"),g=d+g);if(n){d=e(n);if(!d)throw Error("sourceMapURL could not be parsed");d.path&&(n=d.path.lastIndexOf("/"),0<=n&&(d.path=d.path.substring(0,n+1)));g=m(p(d),g)}return t(g)}},{}],20:[function(C,J,A){A.SourceMapGenerator=C("./lib/source-map-generator").SourceMapGenerator;A.SourceMapConsumer=C("./lib/source-map-consumer").SourceMapConsumer;A.SourceNode=C("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16, +"./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(C,J,A){(function(e){function p(){return"browser"===a?!0:"node"===a?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function t(x){return function(B){for(var F=0;F";B=this.getLineNumber();null!=B&&(x+=":"+B,(B= +this.getColumnNumber())&&(x+=":"+B))}B="";var F=this.getFunctionName(),E=!0,H=this.isConstructor();if(this.isToplevel()||H)H?B+="new "+(F||""):F?B+=F:(B+=x,E=!1);else{H=this.getTypeName();"[object Object]"===H&&(H="null");var M=this.getMethodName();F?(H&&0!=F.indexOf(H)&&(B+=H+"."),B+=F,M&&F.indexOf("."+M)!=F.length-M.length-1&&(B+=" [as "+M+"]")):B+=H+"."+(M||"")}E&&(B+=" ("+x+")");return B}function q(x){var B={};Object.getOwnPropertyNames(Object.getPrototypeOf(x)).forEach(function(F){B[F]= +/^(?:is|get)/.test(F)?function(){return x[F].call(x)}:x[F]});B.toString=l;return B}function r(x,B){void 0===B&&(B={nextPosition:null,curPosition:null});if(x.isNative())return B.curPosition=null,x;var F=x.getFileName()||x.getScriptNameOrSourceURL();if(F){var E=x.getLineNumber(),H=x.getColumnNumber()-1,M=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/,S=M.test;var V="object"===typeof e&&null!==e?e.version:"";M=S.call(M,V)?0:62;1===E&&H>M&&!p()&&!x.isEval()&&(H-=M);var O= +f({source:F,line:E,column:H});B.curPosition=O;x=q(x);var T=x.getFunctionName;x.getFunctionName=function(){return null==B.nextPosition?T():B.nextPosition.name||T()};x.getFileName=function(){return O.source};x.getLineNumber=function(){return O.line};x.getColumnNumber=function(){return O.column+1};x.getScriptNameOrSourceURL=function(){return O.source};return x}var Q=x.isEval()&&x.getEvalOrigin();Q&&(Q=c(Q),x=q(x),x.getEvalOrigin=function(){return Q});return x}function k(x,B){L&&(b={},h={});for(var F= +(x.name||"Error")+": "+(x.message||""),E={nextPosition:null,curPosition:null},H=[],M=B.length-1;0<=M;M--)H.push("\n at "+r(B[M],E)),E.nextPosition=E.curPosition;E.curPosition=E.nextPosition=null;return F+H.reverse().join("")}function u(x){var B=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(x.stack);if(B){x=B[1];var F=+B[2];B=+B[3];var E=b[x];if(!E&&v&&v.existsSync(x))try{E=v.readFileSync(x,"utf8")}catch(H){E=""}if(E&&(E=E.split(/(?:\r\n|\r|\n)/)[F-1]))return x+":"+F+"\n"+E+"\n"+Array(B).join(" ")+ +"^"}return null}function d(){var x=e.emit;e.emit=function(B){if("uncaughtException"===B){var F=arguments[1]&&arguments[1].stack,E=0 C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + if (path in fileContentsCache) { + return fileContentsCache[path]; + } + + var contents = ''; + try { + if (!fs) { + // Use SJAX if we are in the browser + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, /** async */ false); + xhr.send(null); + if (xhr.readyState === 4 && xhr.status === 200) { + contents = xhr.responseText; + } + } else if (fs.existsSync(path)) { + // Otherwise, use the filesystem + contents = fs.readFileSync(path, 'utf8'); + } + } catch (er) { + /* ignore any errors */ + } + + return fileContentsCache[path] = contents; +}); + +// Support URLs relative to a directory, but be careful about a protocol prefix +// in case we are in the browser (i.e. directories may start with "http://" or "file:///") +function supportRelativeURL(file, url) { + if (!file) return url; + var dir = path.dirname(file); + var match = /^\w+:\/\/[^\/]*/.exec(dir); + var protocol = match ? match[0] : ''; + var startPath = dir.slice(protocol.length); + if (protocol && /^\/\w\:/.test(startPath)) { + // handle file:///C:/ paths + protocol += '/'; + return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/'); + } + return protocol + path.resolve(dir.slice(protocol.length), url); +} + +function retrieveSourceMapURL(source) { + var fileData; + + if (isInBrowser()) { + try { + var xhr = new XMLHttpRequest(); + xhr.open('GET', source, false); + xhr.send(null); + fileData = xhr.readyState === 4 ? xhr.responseText : null; + + // Support providing a sourceMappingURL via the SourceMap header + var sourceMapHeader = xhr.getResponseHeader("SourceMap") || + xhr.getResponseHeader("X-SourceMap"); + if (sourceMapHeader) { + return sourceMapHeader; + } + } catch (e) { + } + } + + // Get the URL of the source map + fileData = retrieveFile(source); + var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; +}; + +// Can be overridden by the retrieveSourceMap option to install. Takes a +// generated source filename; returns a {map, optional url} object, or null if +// there is no source map. The map field may be either a string or the parsed +// JSON object (ie, it must be a valid argument to the SourceMapConsumer +// constructor). +var retrieveSourceMap = handlerExec(retrieveMapHandlers); +retrieveMapHandlers.push(function(source) { + var sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) return null; + + // Read the contents of the source map + var sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + // Support source map URL as a data url + var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); + sourceMapData = bufferFrom(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(sourceMappingURL); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = sourceMapCache[position.source]; + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = sourceMapCache[position.source] = { + url: urlAndMap.url, + map: new SourceMapConsumer(urlAndMap.map) + }; + + // Load all sources stored inline with the source map into the file cache + // to pretend like they are already loaded. They may not exist on disk. + if (sourceMap.map.sourcesContent) { + sourceMap.map.sources.forEach(function(source, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + var url = supportRelativeURL(sourceMap.url, source); + fileContentsCache[url] = contents; + } + }); + } + } else { + sourceMap = sourceMapCache[position.source] = { + url: null, + map: null + }; + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') { + var originalPosition = sourceMap.map.originalPositionFor(position); + + // Only return the original position if a matching line was found. If no + // matching line is found then we return position instead, which will cause + // the stack trace to print the path and line for the compiled file. It is + // better to give a precise location in the compiled file than a vague + // location in the original file. + if (originalPosition.source !== null) { + originalPosition.source = supportRelativeURL( + sourceMap.url, originalPosition.source); + return originalPosition; + } + } + + return position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition({ + source: match[2], + line: +match[3], + column: match[4] - 1 + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + (position.column + 1) + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +// This is copied almost verbatim from the V8 source code at +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The +// implementation of wrapCallSite() used to just forward to the actual source +// code of CallSite.prototype.toString but unfortunately a new release of V8 +// did something to the prototype chain and broke the shim. The only fix I +// could find was copy/paste. +function CallSiteToString() { + var fileName; + var fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; // Expecting source position to follow. + } + + if (fileName) { + fileLocation += fileName; + } else { + // Source code does not originate from a file and is not native, but we + // can still get the source position inside the source string, e.g. in + // an eval string. + fileLocation += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + var functionName = this.getFunctionName(); + var addSuffix = true; + var isConstructor = this.isConstructor(); + var isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + var typeName = this.getTypeName(); + // Fixes shim to be backward compatable with Node v0 to v4 + if (typeName === "[object Object]") { + typeName = "null"; + } + var methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) != 0) { + line += typeName + "."; + } + line += functionName; + if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { + line += " [as " + methodName + "]"; + } + } else { + line += typeName + "." + (methodName || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) { + line += " (" + fileLocation + ")"; + } + return line; +} + +function cloneCallSite(frame) { + var object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { + object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; + }); + object.toString = CallSiteToString; + return object; +} + +function wrapCallSite(frame, state) { + // provides interface backward compatibility + if (state === undefined) { + state = { nextPosition: null, curPosition: null } + } + if(frame.isNative()) { + state.curPosition = null; + return frame; + } + + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//# sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + var line = frame.getLineNumber(); + var column = frame.getColumnNumber() - 1; + + // Fix position in Node where some (internal) code is prepended. + // See https://github.com/evanw/node-source-map-support/issues/36 + // Header removed in node at ^10.16 || >=11.11.0 + // v11 is not an LTS candidate, we can just test the one version with it. + // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11 + var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; + var headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62; + if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { + column -= headerLength; + } + + var position = mapSourcePosition({ + source: source, + line: line, + column: column + }); + state.curPosition = position; + frame = cloneCallSite(frame); + var originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { + if (state.nextPosition == null) { + return originalFunctionName(); + } + return state.nextPosition.name || originalFunctionName(); + }; + frame.getFileName = function() { return position.source; }; + frame.getLineNumber = function() { return position.line; }; + frame.getColumnNumber = function() { return position.column + 1; }; + frame.getScriptNameOrSourceURL = function() { return position.source; }; + return frame; + } + + // Code called using eval() needs special handling + var origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { return origin; }; + return frame; + } + + // If we get here then we were unable to change the source position + return frame; +} + +// This function is part of the V8 stack trace API, for more info see: +// https://v8.dev/docs/stack-trace-api +function prepareStackTrace(error, stack) { + if (emptyCacheBetweenOperations) { + fileContentsCache = {}; + sourceMapCache = {}; + } + + var name = error.name || 'Error'; + var message = error.message || ''; + var errorString = name + ": " + message; + + var state = { nextPosition: null, curPosition: null }; + var processedStack = []; + for (var i = stack.length - 1; i >= 0; i--) { + processedStack.push('\n at ' + wrapCallSite(stack[i], state)); + state.nextPosition = state.curPosition; + } + state.curPosition = state.nextPosition = null; + return errorString + processedStack.reverse().join(''); +} + +// Generate position and snippet of original source with pointer +function getErrorSource(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var source = match[1]; + var line = +match[2]; + var column = +match[3]; + + // Support the inline sourceContents inside the source map + var contents = fileContentsCache[source]; + + // Support files on disk + if (!contents && fs && fs.existsSync(source)) { + try { + contents = fs.readFileSync(source, 'utf8'); + } catch (er) { + contents = ''; + } + } + + // Format the line from the original source code like node does + if (contents) { + var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; + if (code) { + return source + ':' + line + '\n' + code + '\n' + + new Array(column).join(' ') + '^'; + } + } + } + return null; +} + +function printErrorAndExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + var stderr = globalProcessStderr(); + if (stderr && stderr._handle && stderr._handle.setBlocking) { + stderr._handle.setBlocking(true); + } + + if (source) { + console.error(); + console.error(source); + } + + console.error(error.stack); + globalProcessExit(1); +} + +function shimEmitUncaughtException () { + var origEmit = process.emit; + + process.emit = function (type) { + if (type === 'uncaughtException') { + var hasStack = (arguments[1] && arguments[1].stack); + var hasListeners = (this.listeners(type).length > 0); + + if (hasStack && !hasListeners) { + return printErrorAndExit(arguments[1]); + } + } + + return origEmit.apply(this, arguments); + }; +} + +var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0); + +exports.wrapCallSite = wrapCallSite; +exports.getErrorSource = getErrorSource; +exports.mapSourcePosition = mapSourcePosition; +exports.retrieveSourceMap = retrieveSourceMap; + +exports.install = function(options) { + options = options || {}; + + if (options.environment) { + environment = options.environment; + if (["node", "browser", "auto"].indexOf(environment) === -1) { + throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + retrieveFileHandlers.length = 0; + } + + retrieveFileHandlers.unshift(options.retrieveFile); + } + + // Allow source maps to be found by methods other than reading the files + // directly from disk. + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) { + retrieveMapHandlers.length = 0; + } + + retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + // Use dynamicRequire to avoid including in browser bundles + var Module = dynamicRequire(module, 'module'); + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + fileContentsCache[filename] = content; + sourceMapCache[filename] = undefined; + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!emptyCacheBetweenOperations) { + emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + // Install the error reformatter + if (!errorFormatterInstalled) { + errorFormatterInstalled = true; + Error.prepareStackTrace = prepareStackTrace; + } + + if (!uncaughtShimInstalled) { + var installHandler = 'handleUncaughtExceptions' in options ? + options.handleUncaughtExceptions : true; + + // Do not override 'uncaughtException' with our own handler in Node.js + // Worker threads. Workers pass the error to the main thread as an event, + // rather than printing something to stderr and exiting. + try { + // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify. + var worker_threads = dynamicRequire(module, 'worker_threads'); + if (worker_threads.isMainThread === false) { + installHandler = false; + } + } catch(e) {} + + // Provide the option to not install the uncaught exception handler. This is + // to support other uncaught exception handlers (in test frameworks, for + // example). If this handler is not installed and there are no other uncaught + // exception handlers, uncaught exceptions will be caught by node's built-in + // exception handler and the process will still be terminated. However, the + // generated JavaScript code will be shown above the stack trace instead of + // the original source code. + if (installHandler && hasGlobalProcessEventEmitter()) { + uncaughtShimInstalled = true; + shimEmitUncaughtException(); + } + } +}; + +exports.resetRetrieveHandlers = function() { + retrieveFileHandlers.length = 0; + retrieveMapHandlers.length = 0; + + retrieveFileHandlers = originalRetrieveFileHandlers.slice(0); + retrieveMapHandlers = originalRetrieveMapHandlers.slice(0); + + retrieveSourceMap = handlerExec(retrieveMapHandlers); + retrieveFile = handlerExec(retrieveFileHandlers); +} diff --git a/node_modules/source-map/CHANGELOG.md b/node_modules/source-map/CHANGELOG.md new file mode 100644 index 0000000..3a8c066 --- /dev/null +++ b/node_modules/source-map/CHANGELOG.md @@ -0,0 +1,301 @@ +# Change Log + +## 0.5.6 + +* Fix for regression when people were using numbers as names in source maps. See + #236. + +## 0.5.5 + +* Fix "regression" of unsupported, implementation behavior that half the world + happens to have come to depend on. See #235. + +* Fix regression involving function hoisting in SpiderMonkey. See #233. + +## 0.5.4 + +* Large performance improvements to source-map serialization. See #228 and #229. + +## 0.5.3 + +* Do not include unnecessary distribution files. See + commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86. + +## 0.5.2 + +* Include browser distributions of the library in package.json's `files`. See + issue #212. + +## 0.5.1 + +* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See + ff05274becc9e6e1295ed60f3ea090d31d843379. + +## 0.5.0 + +* Node 0.8 is no longer supported. + +* Use webpack instead of dryice for bundling. + +* Big speedups serializing source maps. See pull request #203. + +* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that + explicitly start with the source root. See issue #199. + +## 0.4.4 + +* Fix an issue where using a `SourceMapGenerator` after having created a + `SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See + issue #191. + +* Fix an issue with where `SourceMapGenerator` would mistakenly consider + different mappings as duplicates of each other and avoid generating them. See + issue #192. + +## 0.4.3 + +* A very large number of performance improvements, particularly when parsing + source maps. Collectively about 75% of time shaved off of the source map + parsing benchmark! + +* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy + searching in the presence of a column option. See issue #177. + +* Fix a bug with joining a source and its source root when the source is above + the root. See issue #182. + +* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to + determine when all sources' contents are inlined into the source map. See + issue #190. + +## 0.4.2 + +* Add an `.npmignore` file so that the benchmarks aren't pulled down by + dependent projects. Issue #169. + +* Add an optional `column` argument to + `SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines + with no mappings. Issues #172 and #173. + +## 0.4.1 + +* Fix accidentally defining a global variable. #170. + +## 0.4.0 + +* The default direction for fuzzy searching was changed back to its original + direction. See #164. + +* There is now a `bias` option you can supply to `SourceMapConsumer` to control + the fuzzy searching direction. See #167. + +* About an 8% speed up in parsing source maps. See #159. + +* Added a benchmark for parsing and generating source maps. + +## 0.3.0 + +* Change the default direction that searching for positions fuzzes when there is + not an exact match. See #154. + +* Support for environments using json2.js for JSON serialization. See #156. + +## 0.2.0 + +* Support for consuming "indexed" source maps which do not have any remote + sections. See pull request #127. This introduces a minor backwards + incompatibility if you are monkey patching `SourceMapConsumer.prototype` + methods. + +## 0.1.43 + +* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue + #148 for some discussion and issues #150, #151, and #152 for implementations. + +## 0.1.42 + +* Fix an issue where `SourceNode`s from different versions of the source-map + library couldn't be used in conjunction with each other. See issue #142. + +## 0.1.41 + +* Fix a bug with getting the source content of relative sources with a "./" + prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768). + +* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the + column span of each mapping. + +* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find + all generated positions associated with a given original source and line. + +## 0.1.40 + +* Performance improvements for parsing source maps in SourceMapConsumer. + +## 0.1.39 + +* Fix a bug where setting a source's contents to null before any source content + had been set before threw a TypeError. See issue #131. + +## 0.1.38 + +* Fix a bug where finding relative paths from an empty path were creating + absolute paths. See issue #129. + +## 0.1.37 + +* Fix a bug where if the source root was an empty string, relative source paths + would turn into absolute source paths. Issue #124. + +## 0.1.36 + +* Allow the `names` mapping property to be an empty string. Issue #121. + +## 0.1.35 + +* A third optional parameter was added to `SourceNode.fromStringWithSourceMap` + to specify a path that relative sources in the second parameter should be + relative to. Issue #105. + +* If no file property is given to a `SourceMapGenerator`, then the resulting + source map will no longer have a `null` file property. The property will + simply not exist. Issue #104. + +* Fixed a bug where consecutive newlines were ignored in `SourceNode`s. + Issue #116. + +## 0.1.34 + +* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103. + +* Fix bug involving source contents and the + `SourceMapGenerator.prototype.applySourceMap`. Issue #100. + +## 0.1.33 + +* Fix some edge cases surrounding path joining and URL resolution. + +* Add a third parameter for relative path to + `SourceMapGenerator.prototype.applySourceMap`. + +* Fix issues with mappings and EOLs. + +## 0.1.32 + +* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns + (issue 92). + +* Fixed test runner to actually report number of failed tests as its process + exit code. + +* Fixed a typo when reporting bad mappings (issue 87). + +## 0.1.31 + +* Delay parsing the mappings in SourceMapConsumer until queried for a source + location. + +* Support Sass source maps (which at the time of writing deviate from the spec + in small ways) in SourceMapConsumer. + +## 0.1.30 + +* Do not join source root with a source, when the source is a data URI. + +* Extend the test runner to allow running single specific test files at a time. + +* Performance improvements in `SourceNode.prototype.walk` and + `SourceMapConsumer.prototype.eachMapping`. + +* Source map browser builds will now work inside Workers. + +* Better error messages when attempting to add an invalid mapping to a + `SourceMapGenerator`. + +## 0.1.29 + +* Allow duplicate entries in the `names` and `sources` arrays of source maps + (usually from TypeScript) we are parsing. Fixes github issue 72. + +## 0.1.28 + +* Skip duplicate mappings when creating source maps from SourceNode; github + issue 75. + +## 0.1.27 + +* Don't throw an error when the `file` property is missing in SourceMapConsumer, + we don't use it anyway. + +## 0.1.26 + +* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70. + +## 0.1.25 + +* Make compatible with browserify + +## 0.1.24 + +* Fix issue with absolute paths and `file://` URIs. See + https://bugzilla.mozilla.org/show_bug.cgi?id=885597 + +## 0.1.23 + +* Fix issue with absolute paths and sourcesContent, github issue 64. + +## 0.1.22 + +* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21. + +## 0.1.21 + +* Fixed handling of sources that start with a slash so that they are relative to + the source root's host. + +## 0.1.20 + +* Fixed github issue #43: absolute URLs aren't joined with the source root + anymore. + +## 0.1.19 + +* Using Travis CI to run tests. + +## 0.1.18 + +* Fixed a bug in the handling of sourceRoot. + +## 0.1.17 + +* Added SourceNode.fromStringWithSourceMap. + +## 0.1.16 + +* Added missing documentation. + +* Fixed the generating of empty mappings in SourceNode. + +## 0.1.15 + +* Added SourceMapGenerator.applySourceMap. + +## 0.1.14 + +* The sourceRoot is now handled consistently. + +## 0.1.13 + +* Added SourceMapGenerator.fromSourceMap. + +## 0.1.12 + +* SourceNode now generates empty mappings too. + +## 0.1.11 + +* Added name support to SourceNode. + +## 0.1.10 + +* Added sourcesContent support to the customer and generator. diff --git a/node_modules/source-map/LICENSE b/node_modules/source-map/LICENSE new file mode 100644 index 0000000..ed1b7cf --- /dev/null +++ b/node_modules/source-map/LICENSE @@ -0,0 +1,28 @@ + +Copyright (c) 2009-2011, Mozilla Foundation and 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: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* 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. + +* Neither the names of the Mozilla Foundation nor the names of project + 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/source-map/README.md b/node_modules/source-map/README.md new file mode 100644 index 0000000..fea4beb --- /dev/null +++ b/node_modules/source-map/README.md @@ -0,0 +1,742 @@ +# Source Map + +[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) + +[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) + +This is a library to generate and consume the source map format +[described here][format]. + +[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit + +## Use with Node + + $ npm install source-map + +## Use on the Web + + + +-------------------------------------------------------------------------------- + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' +}; + +var smc = new SourceMapConsumer(rawSourceMap); + +console.log(smc.sources); +// [ 'http://example.com/www/js/one.js', +// 'http://example.com/www/js/two.js' ] + +console.log(smc.originalPositionFor({ + line: 2, + column: 28 +})); +// { source: 'http://example.com/www/js/two.js', +// line: 2, +// column: 10, +// name: 'n' } + +console.log(smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 +})); +// { line: 2, column: 28 } + +smc.eachMapping(function (m) { + // ... +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } +} + +var ast = parse("40 + 2", "add.js"); +console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' +})); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: "source-mapped.js" +}); + +map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); +``` + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +```js +var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +``` + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] + +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +* `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +* `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +* `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }) +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor("my-cool-lib.clj") +// "..." + +consumer.sourceContentFor("this is not in the source map"); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor("this is not in the source map", true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { console.log(m); }) +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +* `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: "my-generated-javascript-file.js", + sourceRoot: "http://example.com/app/js/" +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +* `sourceMapConsumer` The SourceMap. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: "module-one.scm", + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 } +}) +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +```js +generator.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString() +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, "a.cpp", [ + new SourceNode(3, 4, "b.cpp", "extern int status;\n"), + new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); +var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), + consumer); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(" + "); +node.add(otherNode); +node.add([leftHandOperandNode, " + ", rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend("/** Build Id: f783haef86324gf **/\n\n"); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +```js +node.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, "a.js", "generated from a"); +a.setSourceContent("a.js", "original a"); +var b = new SourceNode(1, 2, "b.js", "generated from b"); +b.setSourceContent("b.js", "original b"); +var c = new SourceNode(1, 2, "c.js", "generated from c"); +c.setSourceContent("c.js", "original c"); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); +var operand = new SourceNode(3, 4, "a.rs", "="); +var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); + +var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var joinedNode = node.join(" "); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ""); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toString() +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toStringWithSourceMap({ file: "my-output-file.js" }) +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/node_modules/source-map/dist/source-map.debug.js b/node_modules/source-map/dist/source-map.debug.js new file mode 100644 index 0000000..aad0620 --- /dev/null +++ b/node_modules/source-map/dist/source-map.debug.js @@ -0,0 +1,3234 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * * Neither the name of Google Inc. 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 + * OWNER 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. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vd2VicGFjay91bml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uIiwid2VicGFjazovLy93ZWJwYWNrL2Jvb3RzdHJhcCAxNjI0YzcyOTliODg3ZjdiZGY2NCIsIndlYnBhY2s6Ly8vLi9zb3VyY2UtbWFwLmpzIiwid2VicGFjazovLy8uL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LXZscS5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LmpzIiwid2VicGFjazovLy8uL2xpYi91dGlsLmpzIiwid2VicGFjazovLy8uL2xpYi9hcnJheS1zZXQuanMiLCJ3ZWJwYWNrOi8vLy4vbGliL21hcHBpbmctbGlzdC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmluYXJ5LXNlYXJjaC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvcXVpY2stc29ydC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW5vZGUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsQ0FBQztBQUNELE87QUNWQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSx1QkFBZTtBQUNmO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7QUFHQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOzs7Ozs7O0FDdENBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNQQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBLE1BQUs7QUFDTDtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsUUFBTztBQUNQO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLDJDQUEwQyxTQUFTO0FBQ25EO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EscUJBQW9CO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7Ozs7OztBQ3hhQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSw0REFBMkQ7QUFDM0QscUJBQW9CO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBRzs7QUFFSDtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7O0FBRUg7QUFDQTtBQUNBOzs7Ozs7O0FDM0lBLGlCQUFnQixvQkFBb0I7QUFDcEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGlCQUFnQjtBQUNoQixpQkFBZ0I7O0FBRWhCLG9CQUFtQjtBQUNuQixxQkFBb0I7O0FBRXBCLGlCQUFnQjtBQUNoQixpQkFBZ0I7O0FBRWhCLGlCQUFnQjtBQUNoQixrQkFBaUI7O0FBRWpCO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7Ozs7O0FDbEVBLGlCQUFnQixvQkFBb0I7QUFDcEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7QUFDSDtBQUNBLElBQUc7QUFDSDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLCtDQUE4QyxRQUFRO0FBQ3REO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsRUFBQzs7QUFFRDtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQSw0QkFBMkIsUUFBUTtBQUNuQztBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLGNBQWE7QUFDYjs7QUFFQTtBQUNBLGVBQWM7QUFDZDs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHVDQUFzQztBQUN0QztBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7Ozs7O0FDdmVBLGlCQUFnQixvQkFBb0I7QUFDcEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHVDQUFzQyxTQUFTO0FBQy9DO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7QUFDSDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBRztBQUNIO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7Ozs7Ozs7QUN4SEEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGlCQUFnQjtBQUNoQjs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxJQUFHO0FBQ0g7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7Ozs7Ozs7QUM5RUEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxFQUFDOztBQUVEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLEVBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0Esb0JBQW1CO0FBQ25COztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFlBQVc7O0FBRVg7QUFDQTtBQUNBLFFBQU87QUFDUDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsWUFBVzs7QUFFWDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsNEJBQTJCLE1BQU07QUFDakM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLOztBQUVMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsSUFBRzs7QUFFSDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLGNBQWEsa0NBQWtDO0FBQy9DO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7O0FBRUw7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBLHVEQUFzRCxZQUFZO0FBQ2xFO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0Esb0NBQW1DO0FBQ25DO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSwwQkFBeUIsY0FBYztBQUN2QztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esd0JBQXVCLHdDQUF3QztBQUMvRDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGdEQUErQyxtQkFBbUIsRUFBRTtBQUNwRTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxrQkFBaUIsb0JBQW9CO0FBQ3JDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSw4QkFBNkIsTUFBTTtBQUNuQztBQUNBLFFBQU87QUFDUDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsUUFBTztBQUNQO0FBQ0E7QUFDQSxJQUFHO0FBQ0g7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBbUIsMkJBQTJCO0FBQzlDLHNCQUFxQiwrQ0FBK0M7QUFDcEU7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsUUFBTztBQUNQOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW1CLDJCQUEyQjtBQUM5Qzs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFtQiwyQkFBMkI7QUFDOUM7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW1CLDJCQUEyQjtBQUM5QztBQUNBO0FBQ0Esc0JBQXFCLDRCQUE0QjtBQUNqRDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTs7Ozs7OztBQ3huQ0EsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7Ozs7Ozs7QUM5R0EsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxZQUFXLE1BQU07QUFDakI7QUFDQSxZQUFXLE9BQU87QUFDbEI7QUFDQSxZQUFXLE9BQU87QUFDbEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsWUFBVyxNQUFNO0FBQ2pCO0FBQ0EsWUFBVyxTQUFTO0FBQ3BCO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0EsWUFBVyxPQUFPO0FBQ2xCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBbUIsT0FBTztBQUMxQjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsWUFBVyxNQUFNO0FBQ2pCO0FBQ0EsWUFBVyxTQUFTO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNqSEEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSzs7QUFFTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esa0NBQWlDLFFBQVE7QUFDekM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsOENBQTZDLFNBQVM7QUFDdEQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EscUJBQW9CO0FBQ3BCO0FBQ0E7QUFDQSx1Q0FBc0M7QUFDdEM7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0JBQWUsV0FBVztBQUMxQjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0RBQStDLFNBQVM7QUFDeEQ7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSwwQ0FBeUMsU0FBUztBQUNsRDtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7QUFDSDtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFlBQVc7QUFDWDtBQUNBO0FBQ0E7QUFDQSxZQUFXO0FBQ1g7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0EsNkNBQTRDLGNBQWM7QUFDMUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGNBQWE7QUFDYjtBQUNBO0FBQ0E7QUFDQSxjQUFhO0FBQ2I7QUFDQSxZQUFXO0FBQ1g7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBO0FBQ0EsSUFBRztBQUNIO0FBQ0E7QUFDQSxJQUFHOztBQUVILFdBQVU7QUFDVjs7QUFFQSIsImZpbGUiOiJzb3VyY2UtbWFwLmRlYnVnLmpzIiwic291cmNlc0NvbnRlbnQiOlsiKGZ1bmN0aW9uIHdlYnBhY2tVbml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uKHJvb3QsIGZhY3RvcnkpIHtcblx0aWYodHlwZW9mIGV4cG9ydHMgPT09ICdvYmplY3QnICYmIHR5cGVvZiBtb2R1bGUgPT09ICdvYmplY3QnKVxuXHRcdG1vZHVsZS5leHBvcnRzID0gZmFjdG9yeSgpO1xuXHRlbHNlIGlmKHR5cGVvZiBkZWZpbmUgPT09ICdmdW5jdGlvbicgJiYgZGVmaW5lLmFtZClcblx0XHRkZWZpbmUoW10sIGZhY3RvcnkpO1xuXHRlbHNlIGlmKHR5cGVvZiBleHBvcnRzID09PSAnb2JqZWN0Jylcblx0XHRleHBvcnRzW1wic291cmNlTWFwXCJdID0gZmFjdG9yeSgpO1xuXHRlbHNlXG5cdFx0cm9vdFtcInNvdXJjZU1hcFwiXSA9IGZhY3RvcnkoKTtcbn0pKHRoaXMsIGZ1bmN0aW9uKCkge1xucmV0dXJuIFxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyB3ZWJwYWNrL3VuaXZlcnNhbE1vZHVsZURlZmluaXRpb24iLCIgXHQvLyBUaGUgbW9kdWxlIGNhY2hlXG4gXHR2YXIgaW5zdGFsbGVkTW9kdWxlcyA9IHt9O1xuXG4gXHQvLyBUaGUgcmVxdWlyZSBmdW5jdGlvblxuIFx0ZnVuY3Rpb24gX193ZWJwYWNrX3JlcXVpcmVfXyhtb2R1bGVJZCkge1xuXG4gXHRcdC8vIENoZWNrIGlmIG1vZHVsZSBpcyBpbiBjYWNoZVxuIFx0XHRpZihpbnN0YWxsZWRNb2R1bGVzW21vZHVsZUlkXSlcbiBcdFx0XHRyZXR1cm4gaW5zdGFsbGVkTW9kdWxlc1ttb2R1bGVJZF0uZXhwb3J0cztcblxuIFx0XHQvLyBDcmVhdGUgYSBuZXcgbW9kdWxlIChhbmQgcHV0IGl0IGludG8gdGhlIGNhY2hlKVxuIFx0XHR2YXIgbW9kdWxlID0gaW5zdGFsbGVkTW9kdWxlc1ttb2R1bGVJZF0gPSB7XG4gXHRcdFx0ZXhwb3J0czoge30sXG4gXHRcdFx0aWQ6IG1vZHVsZUlkLFxuIFx0XHRcdGxvYWRlZDogZmFsc2VcbiBcdFx0fTtcblxuIFx0XHQvLyBFeGVjdXRlIHRoZSBtb2R1bGUgZnVuY3Rpb25cbiBcdFx0bW9kdWxlc1ttb2R1bGVJZF0uY2FsbChtb2R1bGUuZXhwb3J0cywgbW9kdWxlLCBtb2R1bGUuZXhwb3J0cywgX193ZWJwYWNrX3JlcXVpcmVfXyk7XG5cbiBcdFx0Ly8gRmxhZyB0aGUgbW9kdWxlIGFzIGxvYWRlZFxuIFx0XHRtb2R1bGUubG9hZGVkID0gdHJ1ZTtcblxuIFx0XHQvLyBSZXR1cm4gdGhlIGV4cG9ydHMgb2YgdGhlIG1vZHVsZVxuIFx0XHRyZXR1cm4gbW9kdWxlLmV4cG9ydHM7XG4gXHR9XG5cblxuIFx0Ly8gZXhwb3NlIHRoZSBtb2R1bGVzIG9iamVjdCAoX193ZWJwYWNrX21vZHVsZXNfXylcbiBcdF9fd2VicGFja19yZXF1aXJlX18ubSA9IG1vZHVsZXM7XG5cbiBcdC8vIGV4cG9zZSB0aGUgbW9kdWxlIGNhY2hlXG4gXHRfX3dlYnBhY2tfcmVxdWlyZV9fLmMgPSBpbnN0YWxsZWRNb2R1bGVzO1xuXG4gXHQvLyBfX3dlYnBhY2tfcHVibGljX3BhdGhfX1xuIFx0X193ZWJwYWNrX3JlcXVpcmVfXy5wID0gXCJcIjtcblxuIFx0Ly8gTG9hZCBlbnRyeSBtb2R1bGUgYW5kIHJldHVybiBleHBvcnRzXG4gXHRyZXR1cm4gX193ZWJwYWNrX3JlcXVpcmVfXygwKTtcblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyB3ZWJwYWNrL2Jvb3RzdHJhcCAxNjI0YzcyOTliODg3ZjdiZGY2NCIsIi8qXG4gKiBDb3B5cmlnaHQgMjAwOS0yMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRS50eHQgb3I6XG4gKiBodHRwOi8vb3BlbnNvdXJjZS5vcmcvbGljZW5zZXMvQlNELTMtQ2xhdXNlXG4gKi9cbmV4cG9ydHMuU291cmNlTWFwR2VuZXJhdG9yID0gcmVxdWlyZSgnLi9saWIvc291cmNlLW1hcC1nZW5lcmF0b3InKS5Tb3VyY2VNYXBHZW5lcmF0b3I7XG5leHBvcnRzLlNvdXJjZU1hcENvbnN1bWVyID0gcmVxdWlyZSgnLi9saWIvc291cmNlLW1hcC1jb25zdW1lcicpLlNvdXJjZU1hcENvbnN1bWVyO1xuZXhwb3J0cy5Tb3VyY2VOb2RlID0gcmVxdWlyZSgnLi9saWIvc291cmNlLW5vZGUnKS5Tb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9zb3VyY2UtbWFwLmpzXG4vLyBtb2R1bGUgaWQgPSAwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCIsIi8qIC0qLSBNb2RlOiBqczsganMtaW5kZW50LWxldmVsOiAyOyAtKi0gKi9cbi8qXG4gKiBDb3B5cmlnaHQgMjAxMSBNb3ppbGxhIEZvdW5kYXRpb24gYW5kIGNvbnRyaWJ1dG9yc1xuICogTGljZW5zZWQgdW5kZXIgdGhlIE5ldyBCU0QgbGljZW5zZS4gU2VlIExJQ0VOU0Ugb3I6XG4gKiBodHRwOi8vb3BlbnNvdXJjZS5vcmcvbGljZW5zZXMvQlNELTMtQ2xhdXNlXG4gKi9cblxudmFyIGJhc2U2NFZMUSA9IHJlcXVpcmUoJy4vYmFzZTY0LXZscScpO1xudmFyIHV0aWwgPSByZXF1aXJlKCcuL3V0aWwnKTtcbnZhciBBcnJheVNldCA9IHJlcXVpcmUoJy4vYXJyYXktc2V0JykuQXJyYXlTZXQ7XG52YXIgTWFwcGluZ0xpc3QgPSByZXF1aXJlKCcuL21hcHBpbmctbGlzdCcpLk1hcHBpbmdMaXN0O1xuXG4vKipcbiAqIEFuIGluc3RhbmNlIG9mIHRoZSBTb3VyY2VNYXBHZW5lcmF0b3IgcmVwcmVzZW50cyBhIHNvdXJjZSBtYXAgd2hpY2ggaXNcbiAqIGJlaW5nIGJ1aWx0IGluY3JlbWVudGFsbHkuIFlvdSBtYXkgcGFzcyBhbiBvYmplY3Qgd2l0aCB0aGUgZm9sbG93aW5nXG4gKiBwcm9wZXJ0aWVzOlxuICpcbiAqICAgLSBmaWxlOiBUaGUgZmlsZW5hbWUgb2YgdGhlIGdlbmVyYXRlZCBzb3VyY2UuXG4gKiAgIC0gc291cmNlUm9vdDogQSByb290IGZvciBhbGwgcmVsYXRpdmUgVVJMcyBpbiB0aGlzIHNvdXJjZSBtYXAuXG4gKi9cbmZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcihhQXJncykge1xuICBpZiAoIWFBcmdzKSB7XG4gICAgYUFyZ3MgPSB7fTtcbiAgfVxuICB0aGlzLl9maWxlID0gdXRpbC5nZXRBcmcoYUFyZ3MsICdmaWxlJywgbnVsbCk7XG4gIHRoaXMuX3NvdXJjZVJvb3QgPSB1dGlsLmdldEFyZyhhQXJncywgJ3NvdXJjZVJvb3QnLCBudWxsKTtcbiAgdGhpcy5fc2tpcFZhbGlkYXRpb24gPSB1dGlsLmdldEFyZyhhQXJncywgJ3NraXBWYWxpZGF0aW9uJywgZmFsc2UpO1xuICB0aGlzLl9zb3VyY2VzID0gbmV3IEFycmF5U2V0KCk7XG4gIHRoaXMuX25hbWVzID0gbmV3IEFycmF5U2V0KCk7XG4gIHRoaXMuX21hcHBpbmdzID0gbmV3IE1hcHBpbmdMaXN0KCk7XG4gIHRoaXMuX3NvdXJjZXNDb250ZW50cyA9IG51bGw7XG59XG5cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX3ZlcnNpb24gPSAzO1xuXG4vKipcbiAqIENyZWF0ZXMgYSBuZXcgU291cmNlTWFwR2VuZXJhdG9yIGJhc2VkIG9uIGEgU291cmNlTWFwQ29uc3VtZXJcbiAqXG4gKiBAcGFyYW0gYVNvdXJjZU1hcENvbnN1bWVyIFRoZSBTb3VyY2VNYXAuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5mcm9tU291cmNlTWFwID1cbiAgZnVuY3Rpb24gU291cmNlTWFwR2VuZXJhdG9yX2Zyb21Tb3VyY2VNYXAoYVNvdXJjZU1hcENvbnN1bWVyKSB7XG4gICAgdmFyIHNvdXJjZVJvb3QgPSBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlUm9vdDtcbiAgICB2YXIgZ2VuZXJhdG9yID0gbmV3IFNvdXJjZU1hcEdlbmVyYXRvcih7XG4gICAgICBmaWxlOiBhU291cmNlTWFwQ29uc3VtZXIuZmlsZSxcbiAgICAgIHNvdXJjZVJvb3Q6IHNvdXJjZVJvb3RcbiAgICB9KTtcbiAgICBhU291cmNlTWFwQ29uc3VtZXIuZWFjaE1hcHBpbmcoZnVuY3Rpb24gKG1hcHBpbmcpIHtcbiAgICAgIHZhciBuZXdNYXBwaW5nID0ge1xuICAgICAgICBnZW5lcmF0ZWQ6IHtcbiAgICAgICAgICBsaW5lOiBtYXBwaW5nLmdlbmVyYXRlZExpbmUsXG4gICAgICAgICAgY29sdW1uOiBtYXBwaW5nLmdlbmVyYXRlZENvbHVtblxuICAgICAgICB9XG4gICAgICB9O1xuXG4gICAgICBpZiAobWFwcGluZy5zb3VyY2UgIT0gbnVsbCkge1xuICAgICAgICBuZXdNYXBwaW5nLnNvdXJjZSA9IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBpZiAoc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICAgICAgbmV3TWFwcGluZy5zb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIG5ld01hcHBpbmcuc291cmNlKTtcbiAgICAgICAgfVxuXG4gICAgICAgIG5ld01hcHBpbmcub3JpZ2luYWwgPSB7XG4gICAgICAgICAgbGluZTogbWFwcGluZy5vcmlnaW5hbExpbmUsXG4gICAgICAgICAgY29sdW1uOiBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uXG4gICAgICAgIH07XG5cbiAgICAgICAgaWYgKG1hcHBpbmcubmFtZSAhPSBudWxsKSB7XG4gICAgICAgICAgbmV3TWFwcGluZy5uYW1lID0gbWFwcGluZy5uYW1lO1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIGdlbmVyYXRvci5hZGRNYXBwaW5nKG5ld01hcHBpbmcpO1xuICAgIH0pO1xuICAgIGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VzLmZvckVhY2goZnVuY3Rpb24gKHNvdXJjZUZpbGUpIHtcbiAgICAgIHZhciBzb3VyY2VSZWxhdGl2ZSA9IHNvdXJjZUZpbGU7XG4gICAgICBpZiAoc291cmNlUm9vdCAhPT0gbnVsbCkge1xuICAgICAgICBzb3VyY2VSZWxhdGl2ZSA9IHV0aWwucmVsYXRpdmUoc291cmNlUm9vdCwgc291cmNlRmlsZSk7XG4gICAgICB9XG5cbiAgICAgIGlmICghZ2VuZXJhdG9yLl9zb3VyY2VzLmhhcyhzb3VyY2VSZWxhdGl2ZSkpIHtcbiAgICAgICAgZ2VuZXJhdG9yLl9zb3VyY2VzLmFkZChzb3VyY2VSZWxhdGl2ZSk7XG4gICAgICB9XG5cbiAgICAgIHZhciBjb250ZW50ID0gYVNvdXJjZU1hcENvbnN1bWVyLnNvdXJjZUNvbnRlbnRGb3Ioc291cmNlRmlsZSk7XG4gICAgICBpZiAoY29udGVudCAhPSBudWxsKSB7XG4gICAgICAgIGdlbmVyYXRvci5zZXRTb3VyY2VDb250ZW50KHNvdXJjZUZpbGUsIGNvbnRlbnQpO1xuICAgICAgfVxuICAgIH0pO1xuICAgIHJldHVybiBnZW5lcmF0b3I7XG4gIH07XG5cbi8qKlxuICogQWRkIGEgc2luZ2xlIG1hcHBpbmcgZnJvbSBvcmlnaW5hbCBzb3VyY2UgbGluZSBhbmQgY29sdW1uIHRvIHRoZSBnZW5lcmF0ZWRcbiAqIHNvdXJjZSdzIGxpbmUgYW5kIGNvbHVtbiBmb3IgdGhpcyBzb3VyY2UgbWFwIGJlaW5nIGNyZWF0ZWQuIFRoZSBtYXBwaW5nXG4gKiBvYmplY3Qgc2hvdWxkIGhhdmUgdGhlIGZvbGxvd2luZyBwcm9wZXJ0aWVzOlxuICpcbiAqICAgLSBnZW5lcmF0ZWQ6IEFuIG9iamVjdCB3aXRoIHRoZSBnZW5lcmF0ZWQgbGluZSBhbmQgY29sdW1uIHBvc2l0aW9ucy5cbiAqICAgLSBvcmlnaW5hbDogQW4gb2JqZWN0IHdpdGggdGhlIG9yaWdpbmFsIGxpbmUgYW5kIGNvbHVtbiBwb3NpdGlvbnMuXG4gKiAgIC0gc291cmNlOiBUaGUgb3JpZ2luYWwgc291cmNlIGZpbGUgKHJlbGF0aXZlIHRvIHRoZSBzb3VyY2VSb290KS5cbiAqICAgLSBuYW1lOiBBbiBvcHRpb25hbCBvcmlnaW5hbCB0b2tlbiBuYW1lIGZvciB0aGlzIG1hcHBpbmcuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuYWRkTWFwcGluZyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl9hZGRNYXBwaW5nKGFBcmdzKSB7XG4gICAgdmFyIGdlbmVyYXRlZCA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnZ2VuZXJhdGVkJyk7XG4gICAgdmFyIG9yaWdpbmFsID0gdXRpbC5nZXRBcmcoYUFyZ3MsICdvcmlnaW5hbCcsIG51bGwpO1xuICAgIHZhciBzb3VyY2UgPSB1dGlsLmdldEFyZyhhQXJncywgJ3NvdXJjZScsIG51bGwpO1xuICAgIHZhciBuYW1lID0gdXRpbC5nZXRBcmcoYUFyZ3MsICduYW1lJywgbnVsbCk7XG5cbiAgICBpZiAoIXRoaXMuX3NraXBWYWxpZGF0aW9uKSB7XG4gICAgICB0aGlzLl92YWxpZGF0ZU1hcHBpbmcoZ2VuZXJhdGVkLCBvcmlnaW5hbCwgc291cmNlLCBuYW1lKTtcbiAgICB9XG5cbiAgICBpZiAoc291cmNlICE9IG51bGwpIHtcbiAgICAgIHNvdXJjZSA9IFN0cmluZyhzb3VyY2UpO1xuICAgICAgaWYgKCF0aGlzLl9zb3VyY2VzLmhhcyhzb3VyY2UpKSB7XG4gICAgICAgIHRoaXMuX3NvdXJjZXMuYWRkKHNvdXJjZSk7XG4gICAgICB9XG4gICAgfVxuXG4gICAgaWYgKG5hbWUgIT0gbnVsbCkge1xuICAgICAgbmFtZSA9IFN0cmluZyhuYW1lKTtcbiAgICAgIGlmICghdGhpcy5fbmFtZXMuaGFzKG5hbWUpKSB7XG4gICAgICAgIHRoaXMuX25hbWVzLmFkZChuYW1lKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICB0aGlzLl9tYXBwaW5ncy5hZGQoe1xuICAgICAgZ2VuZXJhdGVkTGluZTogZ2VuZXJhdGVkLmxpbmUsXG4gICAgICBnZW5lcmF0ZWRDb2x1bW46IGdlbmVyYXRlZC5jb2x1bW4sXG4gICAgICBvcmlnaW5hbExpbmU6IG9yaWdpbmFsICE9IG51bGwgJiYgb3JpZ2luYWwubGluZSxcbiAgICAgIG9yaWdpbmFsQ29sdW1uOiBvcmlnaW5hbCAhPSBudWxsICYmIG9yaWdpbmFsLmNvbHVtbixcbiAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgbmFtZTogbmFtZVxuICAgIH0pO1xuICB9O1xuXG4vKipcbiAqIFNldCB0aGUgc291cmNlIGNvbnRlbnQgZm9yIGEgc291cmNlIGZpbGUuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuc2V0U291cmNlQ29udGVudCA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl9zZXRTb3VyY2VDb250ZW50KGFTb3VyY2VGaWxlLCBhU291cmNlQ29udGVudCkge1xuICAgIHZhciBzb3VyY2UgPSBhU291cmNlRmlsZTtcbiAgICBpZiAodGhpcy5fc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICBzb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHRoaXMuX3NvdXJjZVJvb3QsIHNvdXJjZSk7XG4gICAgfVxuXG4gICAgaWYgKGFTb3VyY2VDb250ZW50ICE9IG51bGwpIHtcbiAgICAgIC8vIEFkZCB0aGUgc291cmNlIGNvbnRlbnQgdG8gdGhlIF9zb3VyY2VzQ29udGVudHMgbWFwLlxuICAgICAgLy8gQ3JlYXRlIGEgbmV3IF9zb3VyY2VzQ29udGVudHMgbWFwIGlmIHRoZSBwcm9wZXJ0eSBpcyBudWxsLlxuICAgICAgaWYgKCF0aGlzLl9zb3VyY2VzQ29udGVudHMpIHtcbiAgICAgICAgdGhpcy5fc291cmNlc0NvbnRlbnRzID0gT2JqZWN0LmNyZWF0ZShudWxsKTtcbiAgICAgIH1cbiAgICAgIHRoaXMuX3NvdXJjZXNDb250ZW50c1t1dGlsLnRvU2V0U3RyaW5nKHNvdXJjZSldID0gYVNvdXJjZUNvbnRlbnQ7XG4gICAgfSBlbHNlIGlmICh0aGlzLl9zb3VyY2VzQ29udGVudHMpIHtcbiAgICAgIC8vIFJlbW92ZSB0aGUgc291cmNlIGZpbGUgZnJvbSB0aGUgX3NvdXJjZXNDb250ZW50cyBtYXAuXG4gICAgICAvLyBJZiB0aGUgX3NvdXJjZXNDb250ZW50cyBtYXAgaXMgZW1wdHksIHNldCB0aGUgcHJvcGVydHkgdG8gbnVsbC5cbiAgICAgIGRlbGV0ZSB0aGlzLl9zb3VyY2VzQ29udGVudHNbdXRpbC50b1NldFN0cmluZyhzb3VyY2UpXTtcbiAgICAgIGlmIChPYmplY3Qua2V5cyh0aGlzLl9zb3VyY2VzQ29udGVudHMpLmxlbmd0aCA9PT0gMCkge1xuICAgICAgICB0aGlzLl9zb3VyY2VzQ29udGVudHMgPSBudWxsO1xuICAgICAgfVxuICAgIH1cbiAgfTtcblxuLyoqXG4gKiBBcHBsaWVzIHRoZSBtYXBwaW5ncyBvZiBhIHN1Yi1zb3VyY2UtbWFwIGZvciBhIHNwZWNpZmljIHNvdXJjZSBmaWxlIHRvIHRoZVxuICogc291cmNlIG1hcCBiZWluZyBnZW5lcmF0ZWQuIEVhY2ggbWFwcGluZyB0byB0aGUgc3VwcGxpZWQgc291cmNlIGZpbGUgaXNcbiAqIHJld3JpdHRlbiB1c2luZyB0aGUgc3VwcGxpZWQgc291cmNlIG1hcC4gTm90ZTogVGhlIHJlc29sdXRpb24gZm9yIHRoZVxuICogcmVzdWx0aW5nIG1hcHBpbmdzIGlzIHRoZSBtaW5pbWl1bSBvZiB0aGlzIG1hcCBhbmQgdGhlIHN1cHBsaWVkIG1hcC5cbiAqXG4gKiBAcGFyYW0gYVNvdXJjZU1hcENvbnN1bWVyIFRoZSBzb3VyY2UgbWFwIHRvIGJlIGFwcGxpZWQuXG4gKiBAcGFyYW0gYVNvdXJjZUZpbGUgT3B0aW9uYWwuIFRoZSBmaWxlbmFtZSBvZiB0aGUgc291cmNlIGZpbGUuXG4gKiAgICAgICAgSWYgb21pdHRlZCwgU291cmNlTWFwQ29uc3VtZXIncyBmaWxlIHByb3BlcnR5IHdpbGwgYmUgdXNlZC5cbiAqIEBwYXJhbSBhU291cmNlTWFwUGF0aCBPcHRpb25hbC4gVGhlIGRpcm5hbWUgb2YgdGhlIHBhdGggdG8gdGhlIHNvdXJjZSBtYXBcbiAqICAgICAgICB0byBiZSBhcHBsaWVkLiBJZiByZWxhdGl2ZSwgaXQgaXMgcmVsYXRpdmUgdG8gdGhlIFNvdXJjZU1hcENvbnN1bWVyLlxuICogICAgICAgIFRoaXMgcGFyYW1ldGVyIGlzIG5lZWRlZCB3aGVuIHRoZSB0d28gc291cmNlIG1hcHMgYXJlbid0IGluIHRoZSBzYW1lXG4gKiAgICAgICAgZGlyZWN0b3J5LCBhbmQgdGhlIHNvdXJjZSBtYXAgdG8gYmUgYXBwbGllZCBjb250YWlucyByZWxhdGl2ZSBzb3VyY2VcbiAqICAgICAgICBwYXRocy4gSWYgc28sIHRob3NlIHJlbGF0aXZlIHNvdXJjZSBwYXRocyBuZWVkIHRvIGJlIHJld3JpdHRlblxuICogICAgICAgIHJlbGF0aXZlIHRvIHRoZSBTb3VyY2VNYXBHZW5lcmF0b3IuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuYXBwbHlTb3VyY2VNYXAgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfYXBwbHlTb3VyY2VNYXAoYVNvdXJjZU1hcENvbnN1bWVyLCBhU291cmNlRmlsZSwgYVNvdXJjZU1hcFBhdGgpIHtcbiAgICB2YXIgc291cmNlRmlsZSA9IGFTb3VyY2VGaWxlO1xuICAgIC8vIElmIGFTb3VyY2VGaWxlIGlzIG9taXR0ZWQsIHdlIHdpbGwgdXNlIHRoZSBmaWxlIHByb3BlcnR5IG9mIHRoZSBTb3VyY2VNYXBcbiAgICBpZiAoYVNvdXJjZUZpbGUgPT0gbnVsbCkge1xuICAgICAgaWYgKGFTb3VyY2VNYXBDb25zdW1lci5maWxlID09IG51bGwpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKFxuICAgICAgICAgICdTb3VyY2VNYXBHZW5lcmF0b3IucHJvdG90eXBlLmFwcGx5U291cmNlTWFwIHJlcXVpcmVzIGVpdGhlciBhbiBleHBsaWNpdCBzb3VyY2UgZmlsZSwgJyArXG4gICAgICAgICAgJ29yIHRoZSBzb3VyY2UgbWFwXFwncyBcImZpbGVcIiBwcm9wZXJ0eS4gQm90aCB3ZXJlIG9taXR0ZWQuJ1xuICAgICAgICApO1xuICAgICAgfVxuICAgICAgc291cmNlRmlsZSA9IGFTb3VyY2VNYXBDb25zdW1lci5maWxlO1xuICAgIH1cbiAgICB2YXIgc291cmNlUm9vdCA9IHRoaXMuX3NvdXJjZVJvb3Q7XG4gICAgLy8gTWFrZSBcInNvdXJjZUZpbGVcIiByZWxhdGl2ZSBpZiBhbiBhYnNvbHV0ZSBVcmwgaXMgcGFzc2VkLlxuICAgIGlmIChzb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgIHNvdXJjZUZpbGUgPSB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIHNvdXJjZUZpbGUpO1xuICAgIH1cbiAgICAvLyBBcHBseWluZyB0aGUgU291cmNlTWFwIGNhbiBhZGQgYW5kIHJlbW92ZSBpdGVtcyBmcm9tIHRoZSBzb3VyY2VzIGFuZFxuICAgIC8vIHRoZSBuYW1lcyBhcnJheS5cbiAgICB2YXIgbmV3U291cmNlcyA9IG5ldyBBcnJheVNldCgpO1xuICAgIHZhciBuZXdOYW1lcyA9IG5ldyBBcnJheVNldCgpO1xuXG4gICAgLy8gRmluZCBtYXBwaW5ncyBmb3IgdGhlIFwic291cmNlRmlsZVwiXG4gICAgdGhpcy5fbWFwcGluZ3MudW5zb3J0ZWRGb3JFYWNoKGZ1bmN0aW9uIChtYXBwaW5nKSB7XG4gICAgICBpZiAobWFwcGluZy5zb3VyY2UgPT09IHNvdXJjZUZpbGUgJiYgbWFwcGluZy5vcmlnaW5hbExpbmUgIT0gbnVsbCkge1xuICAgICAgICAvLyBDaGVjayBpZiBpdCBjYW4gYmUgbWFwcGVkIGJ5IHRoZSBzb3VyY2UgbWFwLCB0aGVuIHVwZGF0ZSB0aGUgbWFwcGluZy5cbiAgICAgICAgdmFyIG9yaWdpbmFsID0gYVNvdXJjZU1hcENvbnN1bWVyLm9yaWdpbmFsUG9zaXRpb25Gb3Ioe1xuICAgICAgICAgIGxpbmU6IG1hcHBpbmcub3JpZ2luYWxMaW5lLFxuICAgICAgICAgIGNvbHVtbjogbWFwcGluZy5vcmlnaW5hbENvbHVtblxuICAgICAgICB9KTtcbiAgICAgICAgaWYgKG9yaWdpbmFsLnNvdXJjZSAhPSBudWxsKSB7XG4gICAgICAgICAgLy8gQ29weSBtYXBwaW5nXG4gICAgICAgICAgbWFwcGluZy5zb3VyY2UgPSBvcmlnaW5hbC5zb3VyY2U7XG4gICAgICAgICAgaWYgKGFTb3VyY2VNYXBQYXRoICE9IG51bGwpIHtcbiAgICAgICAgICAgIG1hcHBpbmcuc291cmNlID0gdXRpbC5qb2luKGFTb3VyY2VNYXBQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICB9XG4gICAgICAgICAgaWYgKHNvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgICAgICAgICAgbWFwcGluZy5zb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIG1hcHBpbmcuc291cmNlKTtcbiAgICAgICAgICB9XG4gICAgICAgICAgbWFwcGluZy5vcmlnaW5hbExpbmUgPSBvcmlnaW5hbC5saW5lO1xuICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxDb2x1bW4gPSBvcmlnaW5hbC5jb2x1bW47XG4gICAgICAgICAgaWYgKG9yaWdpbmFsLm5hbWUgIT0gbnVsbCkge1xuICAgICAgICAgICAgbWFwcGluZy5uYW1lID0gb3JpZ2luYWwubmFtZTtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgdmFyIHNvdXJjZSA9IG1hcHBpbmcuc291cmNlO1xuICAgICAgaWYgKHNvdXJjZSAhPSBudWxsICYmICFuZXdTb3VyY2VzLmhhcyhzb3VyY2UpKSB7XG4gICAgICAgIG5ld1NvdXJjZXMuYWRkKHNvdXJjZSk7XG4gICAgICB9XG5cbiAgICAgIHZhciBuYW1lID0gbWFwcGluZy5uYW1lO1xuICAgICAgaWYgKG5hbWUgIT0gbnVsbCAmJiAhbmV3TmFtZXMuaGFzKG5hbWUpKSB7XG4gICAgICAgIG5ld05hbWVzLmFkZChuYW1lKTtcbiAgICAgIH1cblxuICAgIH0sIHRoaXMpO1xuICAgIHRoaXMuX3NvdXJjZXMgPSBuZXdTb3VyY2VzO1xuICAgIHRoaXMuX25hbWVzID0gbmV3TmFtZXM7XG5cbiAgICAvLyBDb3B5IHNvdXJjZXNDb250ZW50cyBvZiBhcHBsaWVkIG1hcC5cbiAgICBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlcy5mb3JFYWNoKGZ1bmN0aW9uIChzb3VyY2VGaWxlKSB7XG4gICAgICB2YXIgY29udGVudCA9IGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKHNvdXJjZUZpbGUpO1xuICAgICAgaWYgKGNvbnRlbnQgIT0gbnVsbCkge1xuICAgICAgICBpZiAoYVNvdXJjZU1hcFBhdGggIT0gbnVsbCkge1xuICAgICAgICAgIHNvdXJjZUZpbGUgPSB1dGlsLmpvaW4oYVNvdXJjZU1hcFBhdGgsIHNvdXJjZUZpbGUpO1xuICAgICAgICB9XG4gICAgICAgIGlmIChzb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgICAgICBzb3VyY2VGaWxlID0gdXRpbC5yZWxhdGl2ZShzb3VyY2VSb290LCBzb3VyY2VGaWxlKTtcbiAgICAgICAgfVxuICAgICAgICB0aGlzLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSwgdGhpcyk7XG4gIH07XG5cbi8qKlxuICogQSBtYXBwaW5nIGNhbiBoYXZlIG9uZSBvZiB0aGUgdGhyZWUgbGV2ZWxzIG9mIGRhdGE6XG4gKlxuICogICAxLiBKdXN0IHRoZSBnZW5lcmF0ZWQgcG9zaXRpb24uXG4gKiAgIDIuIFRoZSBHZW5lcmF0ZWQgcG9zaXRpb24sIG9yaWdpbmFsIHBvc2l0aW9uLCBhbmQgb3JpZ2luYWwgc291cmNlLlxuICogICAzLiBHZW5lcmF0ZWQgYW5kIG9yaWdpbmFsIHBvc2l0aW9uLCBvcmlnaW5hbCBzb3VyY2UsIGFzIHdlbGwgYXMgYSBuYW1lXG4gKiAgICAgIHRva2VuLlxuICpcbiAqIFRvIG1haW50YWluIGNvbnNpc3RlbmN5LCB3ZSB2YWxpZGF0ZSB0aGF0IGFueSBuZXcgbWFwcGluZyBiZWluZyBhZGRlZCBmYWxsc1xuICogaW4gdG8gb25lIG9mIHRoZXNlIGNhdGVnb3JpZXMuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX3ZhbGlkYXRlTWFwcGluZyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl92YWxpZGF0ZU1hcHBpbmcoYUdlbmVyYXRlZCwgYU9yaWdpbmFsLCBhU291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGFOYW1lKSB7XG4gICAgLy8gV2hlbiBhT3JpZ2luYWwgaXMgdHJ1dGh5IGJ1dCBoYXMgZW1wdHkgdmFsdWVzIGZvciAubGluZSBhbmQgLmNvbHVtbixcbiAgICAvLyBpdCBpcyBtb3N0IGxpa2VseSBhIHByb2dyYW1tZXIgZXJyb3IuIEluIHRoaXMgY2FzZSB3ZSB0aHJvdyBhIHZlcnlcbiAgICAvLyBzcGVjaWZpYyBlcnJvciBtZXNzYWdlIHRvIHRyeSB0byBndWlkZSB0aGVtIHRoZSByaWdodCB3YXkuXG4gICAgLy8gRm9yIGV4YW1wbGU6IGh0dHBzOi8vZ2l0aHViLmNvbS9Qb2x5bWVyL3BvbHltZXItYnVuZGxlci9wdWxsLzUxOVxuICAgIGlmIChhT3JpZ2luYWwgJiYgdHlwZW9mIGFPcmlnaW5hbC5saW5lICE9PSAnbnVtYmVyJyAmJiB0eXBlb2YgYU9yaWdpbmFsLmNvbHVtbiAhPT0gJ251bWJlcicpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKFxuICAgICAgICAgICAgJ29yaWdpbmFsLmxpbmUgYW5kIG9yaWdpbmFsLmNvbHVtbiBhcmUgbm90IG51bWJlcnMgLS0geW91IHByb2JhYmx5IG1lYW50IHRvIG9taXQgJyArXG4gICAgICAgICAgICAndGhlIG9yaWdpbmFsIG1hcHBpbmcgZW50aXJlbHkgYW5kIG9ubHkgbWFwIHRoZSBnZW5lcmF0ZWQgcG9zaXRpb24uIElmIHNvLCBwYXNzICcgK1xuICAgICAgICAgICAgJ251bGwgZm9yIHRoZSBvcmlnaW5hbCBtYXBwaW5nIGluc3RlYWQgb2YgYW4gb2JqZWN0IHdpdGggZW1wdHkgb3IgbnVsbCB2YWx1ZXMuJ1xuICAgICAgICApO1xuICAgIH1cblxuICAgIGlmIChhR2VuZXJhdGVkICYmICdsaW5lJyBpbiBhR2VuZXJhdGVkICYmICdjb2x1bW4nIGluIGFHZW5lcmF0ZWRcbiAgICAgICAgJiYgYUdlbmVyYXRlZC5saW5lID4gMCAmJiBhR2VuZXJhdGVkLmNvbHVtbiA+PSAwXG4gICAgICAgICYmICFhT3JpZ2luYWwgJiYgIWFTb3VyY2UgJiYgIWFOYW1lKSB7XG4gICAgICAvLyBDYXNlIDEuXG4gICAgICByZXR1cm47XG4gICAgfVxuICAgIGVsc2UgaWYgKGFHZW5lcmF0ZWQgJiYgJ2xpbmUnIGluIGFHZW5lcmF0ZWQgJiYgJ2NvbHVtbicgaW4gYUdlbmVyYXRlZFxuICAgICAgICAgICAgICYmIGFPcmlnaW5hbCAmJiAnbGluZScgaW4gYU9yaWdpbmFsICYmICdjb2x1bW4nIGluIGFPcmlnaW5hbFxuICAgICAgICAgICAgICYmIGFHZW5lcmF0ZWQubGluZSA+IDAgJiYgYUdlbmVyYXRlZC5jb2x1bW4gPj0gMFxuICAgICAgICAgICAgICYmIGFPcmlnaW5hbC5saW5lID4gMCAmJiBhT3JpZ2luYWwuY29sdW1uID49IDBcbiAgICAgICAgICAgICAmJiBhU291cmNlKSB7XG4gICAgICAvLyBDYXNlcyAyIGFuZCAzLlxuICAgICAgcmV0dXJuO1xuICAgIH1cbiAgICBlbHNlIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignSW52YWxpZCBtYXBwaW5nOiAnICsgSlNPTi5zdHJpbmdpZnkoe1xuICAgICAgICBnZW5lcmF0ZWQ6IGFHZW5lcmF0ZWQsXG4gICAgICAgIHNvdXJjZTogYVNvdXJjZSxcbiAgICAgICAgb3JpZ2luYWw6IGFPcmlnaW5hbCxcbiAgICAgICAgbmFtZTogYU5hbWVcbiAgICAgIH0pKTtcbiAgICB9XG4gIH07XG5cbi8qKlxuICogU2VyaWFsaXplIHRoZSBhY2N1bXVsYXRlZCBtYXBwaW5ncyBpbiB0byB0aGUgc3RyZWFtIG9mIGJhc2UgNjQgVkxRc1xuICogc3BlY2lmaWVkIGJ5IHRoZSBzb3VyY2UgbWFwIGZvcm1hdC5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS5fc2VyaWFsaXplTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3Jfc2VyaWFsaXplTWFwcGluZ3MoKSB7XG4gICAgdmFyIHByZXZpb3VzR2VuZXJhdGVkQ29sdW1uID0gMDtcbiAgICB2YXIgcHJldmlvdXNHZW5lcmF0ZWRMaW5lID0gMTtcbiAgICB2YXIgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gMDtcbiAgICB2YXIgcHJldmlvdXNOYW1lID0gMDtcbiAgICB2YXIgcHJldmlvdXNTb3VyY2UgPSAwO1xuICAgIHZhciByZXN1bHQgPSAnJztcbiAgICB2YXIgbmV4dDtcbiAgICB2YXIgbWFwcGluZztcbiAgICB2YXIgbmFtZUlkeDtcbiAgICB2YXIgc291cmNlSWR4O1xuXG4gICAgdmFyIG1hcHBpbmdzID0gdGhpcy5fbWFwcGluZ3MudG9BcnJheSgpO1xuICAgIGZvciAodmFyIGkgPSAwLCBsZW4gPSBtYXBwaW5ncy5sZW5ndGg7IGkgPCBsZW47IGkrKykge1xuICAgICAgbWFwcGluZyA9IG1hcHBpbmdzW2ldO1xuICAgICAgbmV4dCA9ICcnXG5cbiAgICAgIGlmIChtYXBwaW5nLmdlbmVyYXRlZExpbmUgIT09IHByZXZpb3VzR2VuZXJhdGVkTGluZSkge1xuICAgICAgICBwcmV2aW91c0dlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgICAgIHdoaWxlIChtYXBwaW5nLmdlbmVyYXRlZExpbmUgIT09IHByZXZpb3VzR2VuZXJhdGVkTGluZSkge1xuICAgICAgICAgIG5leHQgKz0gJzsnO1xuICAgICAgICAgIHByZXZpb3VzR2VuZXJhdGVkTGluZSsrO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgICBlbHNlIHtcbiAgICAgICAgaWYgKGkgPiAwKSB7XG4gICAgICAgICAgaWYgKCF1dGlsLmNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0luZmxhdGVkKG1hcHBpbmcsIG1hcHBpbmdzW2kgLSAxXSkpIHtcbiAgICAgICAgICAgIGNvbnRpbnVlO1xuICAgICAgICAgIH1cbiAgICAgICAgICBuZXh0ICs9ICcsJztcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5nZW5lcmF0ZWRDb2x1bW5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgaWYgKG1hcHBpbmcuc291cmNlICE9IG51bGwpIHtcbiAgICAgICAgc291cmNlSWR4ID0gdGhpcy5fc291cmNlcy5pbmRleE9mKG1hcHBpbmcuc291cmNlKTtcbiAgICAgICAgbmV4dCArPSBiYXNlNjRWTFEuZW5jb2RlKHNvdXJjZUlkeCAtIHByZXZpb3VzU291cmNlKTtcbiAgICAgICAgcHJldmlvdXNTb3VyY2UgPSBzb3VyY2VJZHg7XG5cbiAgICAgICAgLy8gbGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkIGluIFNvdXJjZU1hcCBzcGVjIHZlcnNpb24gM1xuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbExpbmUgLSAxXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNPcmlnaW5hbExpbmUpO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsTGluZSA9IG1hcHBpbmcub3JpZ2luYWxMaW5lIC0gMTtcblxuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbENvbHVtblxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtIHByZXZpb3VzT3JpZ2luYWxDb2x1bW4pO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsQ29sdW1uID0gbWFwcGluZy5vcmlnaW5hbENvbHVtbjtcblxuICAgICAgICBpZiAobWFwcGluZy5uYW1lICE9IG51bGwpIHtcbiAgICAgICAgICBuYW1lSWR4ID0gdGhpcy5fbmFtZXMuaW5kZXhPZihtYXBwaW5nLm5hbWUpO1xuICAgICAgICAgIG5leHQgKz0gYmFzZTY0VkxRLmVuY29kZShuYW1lSWR4IC0gcHJldmlvdXNOYW1lKTtcbiAgICAgICAgICBwcmV2aW91c05hbWUgPSBuYW1lSWR4O1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIHJlc3VsdCArPSBuZXh0O1xuICAgIH1cblxuICAgIHJldHVybiByZXN1bHQ7XG4gIH07XG5cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX2dlbmVyYXRlU291cmNlc0NvbnRlbnQgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfZ2VuZXJhdGVTb3VyY2VzQ29udGVudChhU291cmNlcywgYVNvdXJjZVJvb3QpIHtcbiAgICByZXR1cm4gYVNvdXJjZXMubWFwKGZ1bmN0aW9uIChzb3VyY2UpIHtcbiAgICAgIGlmICghdGhpcy5fc291cmNlc0NvbnRlbnRzKSB7XG4gICAgICAgIHJldHVybiBudWxsO1xuICAgICAgfVxuICAgICAgaWYgKGFTb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgICAgc291cmNlID0gdXRpbC5yZWxhdGl2ZShhU291cmNlUm9vdCwgc291cmNlKTtcbiAgICAgIH1cbiAgICAgIHZhciBrZXkgPSB1dGlsLnRvU2V0U3RyaW5nKHNvdXJjZSk7XG4gICAgICByZXR1cm4gT2JqZWN0LnByb3RvdHlwZS5oYXNPd25Qcm9wZXJ0eS5jYWxsKHRoaXMuX3NvdXJjZXNDb250ZW50cywga2V5KVxuICAgICAgICA/IHRoaXMuX3NvdXJjZXNDb250ZW50c1trZXldXG4gICAgICAgIDogbnVsbDtcbiAgICB9LCB0aGlzKTtcbiAgfTtcblxuLyoqXG4gKiBFeHRlcm5hbGl6ZSB0aGUgc291cmNlIG1hcC5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS50b0pTT04gPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfdG9KU09OKCkge1xuICAgIHZhciBtYXAgPSB7XG4gICAgICB2ZXJzaW9uOiB0aGlzLl92ZXJzaW9uLFxuICAgICAgc291cmNlczogdGhpcy5fc291cmNlcy50b0FycmF5KCksXG4gICAgICBuYW1lczogdGhpcy5fbmFtZXMudG9BcnJheSgpLFxuICAgICAgbWFwcGluZ3M6IHRoaXMuX3NlcmlhbGl6ZU1hcHBpbmdzKClcbiAgICB9O1xuICAgIGlmICh0aGlzLl9maWxlICE9IG51bGwpIHtcbiAgICAgIG1hcC5maWxlID0gdGhpcy5fZmlsZTtcbiAgICB9XG4gICAgaWYgKHRoaXMuX3NvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgICAgbWFwLnNvdXJjZVJvb3QgPSB0aGlzLl9zb3VyY2VSb290O1xuICAgIH1cbiAgICBpZiAodGhpcy5fc291cmNlc0NvbnRlbnRzKSB7XG4gICAgICBtYXAuc291cmNlc0NvbnRlbnQgPSB0aGlzLl9nZW5lcmF0ZVNvdXJjZXNDb250ZW50KG1hcC5zb3VyY2VzLCBtYXAuc291cmNlUm9vdCk7XG4gICAgfVxuXG4gICAgcmV0dXJuIG1hcDtcbiAgfTtcblxuLyoqXG4gKiBSZW5kZXIgdGhlIHNvdXJjZSBtYXAgYmVpbmcgZ2VuZXJhdGVkIHRvIGEgc3RyaW5nLlxuICovXG5Tb3VyY2VNYXBHZW5lcmF0b3IucHJvdG90eXBlLnRvU3RyaW5nID1cbiAgZnVuY3Rpb24gU291cmNlTWFwR2VuZXJhdG9yX3RvU3RyaW5nKCkge1xuICAgIHJldHVybiBKU09OLnN0cmluZ2lmeSh0aGlzLnRvSlNPTigpKTtcbiAgfTtcblxuZXhwb3J0cy5Tb3VyY2VNYXBHZW5lcmF0b3IgPSBTb3VyY2VNYXBHZW5lcmF0b3I7XG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qc1xuLy8gbW9kdWxlIGlkID0gMVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICpcbiAqIEJhc2VkIG9uIHRoZSBCYXNlIDY0IFZMUSBpbXBsZW1lbnRhdGlvbiBpbiBDbG9zdXJlIENvbXBpbGVyOlxuICogaHR0cHM6Ly9jb2RlLmdvb2dsZS5jb20vcC9jbG9zdXJlLWNvbXBpbGVyL3NvdXJjZS9icm93c2UvdHJ1bmsvc3JjL2NvbS9nb29nbGUvZGVidWdnaW5nL3NvdXJjZW1hcC9CYXNlNjRWTFEuamF2YVxuICpcbiAqIENvcHlyaWdodCAyMDExIFRoZSBDbG9zdXJlIENvbXBpbGVyIEF1dGhvcnMuIEFsbCByaWdodHMgcmVzZXJ2ZWQuXG4gKiBSZWRpc3RyaWJ1dGlvbiBhbmQgdXNlIGluIHNvdXJjZSBhbmQgYmluYXJ5IGZvcm1zLCB3aXRoIG9yIHdpdGhvdXRcbiAqIG1vZGlmaWNhdGlvbiwgYXJlIHBlcm1pdHRlZCBwcm92aWRlZCB0aGF0IHRoZSBmb2xsb3dpbmcgY29uZGl0aW9ucyBhcmVcbiAqIG1ldDpcbiAqXG4gKiAgKiBSZWRpc3RyaWJ1dGlvbnMgb2Ygc291cmNlIGNvZGUgbXVzdCByZXRhaW4gdGhlIGFib3ZlIGNvcHlyaWdodFxuICogICAgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZyBkaXNjbGFpbWVyLlxuICogICogUmVkaXN0cmlidXRpb25zIGluIGJpbmFyeSBmb3JtIG11c3QgcmVwcm9kdWNlIHRoZSBhYm92ZVxuICogICAgY29weXJpZ2h0IG5vdGljZSwgdGhpcyBsaXN0IG9mIGNvbmRpdGlvbnMgYW5kIHRoZSBmb2xsb3dpbmdcbiAqICAgIGRpc2NsYWltZXIgaW4gdGhlIGRvY3VtZW50YXRpb24gYW5kL29yIG90aGVyIG1hdGVyaWFscyBwcm92aWRlZFxuICogICAgd2l0aCB0aGUgZGlzdHJpYnV0aW9uLlxuICogICogTmVpdGhlciB0aGUgbmFtZSBvZiBHb29nbGUgSW5jLiBub3IgdGhlIG5hbWVzIG9mIGl0c1xuICogICAgY29udHJpYnV0b3JzIG1heSBiZSB1c2VkIHRvIGVuZG9yc2Ugb3IgcHJvbW90ZSBwcm9kdWN0cyBkZXJpdmVkXG4gKiAgICBmcm9tIHRoaXMgc29mdHdhcmUgd2l0aG91dCBzcGVjaWZpYyBwcmlvciB3cml0dGVuIHBlcm1pc3Npb24uXG4gKlxuICogVEhJUyBTT0ZUV0FSRSBJUyBQUk9WSURFRCBCWSBUSEUgQ09QWVJJR0hUIEhPTERFUlMgQU5EIENPTlRSSUJVVE9SU1xuICogXCJBUyBJU1wiIEFORCBBTlkgRVhQUkVTUyBPUiBJTVBMSUVEIFdBUlJBTlRJRVMsIElOQ0xVRElORywgQlVUIE5PVFxuICogTElNSVRFRCBUTywgVEhFIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkgQU5EIEZJVE5FU1MgRk9SXG4gKiBBIFBBUlRJQ1VMQVIgUFVSUE9TRSBBUkUgRElTQ0xBSU1FRC4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIENPUFlSSUdIVFxuICogT1dORVIgT1IgQ09OVFJJQlVUT1JTIEJFIExJQUJMRSBGT1IgQU5ZIERJUkVDVCwgSU5ESVJFQ1QsIElOQ0lERU5UQUwsXG4gKiBTUEVDSUFMLCBFWEVNUExBUlksIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyAoSU5DTFVESU5HLCBCVVQgTk9UXG4gKiBMSU1JVEVEIFRPLCBQUk9DVVJFTUVOVCBPRiBTVUJTVElUVVRFIEdPT0RTIE9SIFNFUlZJQ0VTOyBMT1NTIE9GIFVTRSxcbiAqIERBVEEsIE9SIFBST0ZJVFM7IE9SIEJVU0lORVNTIElOVEVSUlVQVElPTikgSE9XRVZFUiBDQVVTRUQgQU5EIE9OIEFOWVxuICogVEhFT1JZIE9GIExJQUJJTElUWSwgV0hFVEhFUiBJTiBDT05UUkFDVCwgU1RSSUNUIExJQUJJTElUWSwgT1IgVE9SVFxuICogKElOQ0xVRElORyBORUdMSUdFTkNFIE9SIE9USEVSV0lTRSkgQVJJU0lORyBJTiBBTlkgV0FZIE9VVCBPRiBUSEUgVVNFXG4gKiBPRiBUSElTIFNPRlRXQVJFLCBFVkVOIElGIEFEVklTRUQgT0YgVEhFIFBPU1NJQklMSVRZIE9GIFNVQ0ggREFNQUdFLlxuICovXG5cbnZhciBiYXNlNjQgPSByZXF1aXJlKCcuL2Jhc2U2NCcpO1xuXG4vLyBBIHNpbmdsZSBiYXNlIDY0IGRpZ2l0IGNhbiBjb250YWluIDYgYml0cyBvZiBkYXRhLiBGb3IgdGhlIGJhc2UgNjQgdmFyaWFibGVcbi8vIGxlbmd0aCBxdWFudGl0aWVzIHdlIHVzZSBpbiB0aGUgc291cmNlIG1hcCBzcGVjLCB0aGUgZmlyc3QgYml0IGlzIHRoZSBzaWduLFxuLy8gdGhlIG5leHQgZm91ciBiaXRzIGFyZSB0aGUgYWN0dWFsIHZhbHVlLCBhbmQgdGhlIDZ0aCBiaXQgaXMgdGhlXG4vLyBjb250aW51YXRpb24gYml0LiBUaGUgY29udGludWF0aW9uIGJpdCB0ZWxscyB1cyB3aGV0aGVyIHRoZXJlIGFyZSBtb3JlXG4vLyBkaWdpdHMgaW4gdGhpcyB2YWx1ZSBmb2xsb3dpbmcgdGhpcyBkaWdpdC5cbi8vXG4vLyAgIENvbnRpbnVhdGlvblxuLy8gICB8ICAgIFNpZ25cbi8vICAgfCAgICB8XG4vLyAgIFYgICAgVlxuLy8gICAxMDEwMTFcblxudmFyIFZMUV9CQVNFX1NISUZUID0gNTtcblxuLy8gYmluYXJ5OiAxMDAwMDBcbnZhciBWTFFfQkFTRSA9IDEgPDwgVkxRX0JBU0VfU0hJRlQ7XG5cbi8vIGJpbmFyeTogMDExMTExXG52YXIgVkxRX0JBU0VfTUFTSyA9IFZMUV9CQVNFIC0gMTtcblxuLy8gYmluYXJ5OiAxMDAwMDBcbnZhciBWTFFfQ09OVElOVUFUSU9OX0JJVCA9IFZMUV9CQVNFO1xuXG4vKipcbiAqIENvbnZlcnRzIGZyb20gYSB0d28tY29tcGxlbWVudCB2YWx1ZSB0byBhIHZhbHVlIHdoZXJlIHRoZSBzaWduIGJpdCBpc1xuICogcGxhY2VkIGluIHRoZSBsZWFzdCBzaWduaWZpY2FudCBiaXQuICBGb3IgZXhhbXBsZSwgYXMgZGVjaW1hbHM6XG4gKiAgIDEgYmVjb21lcyAyICgxMCBiaW5hcnkpLCAtMSBiZWNvbWVzIDMgKDExIGJpbmFyeSlcbiAqICAgMiBiZWNvbWVzIDQgKDEwMCBiaW5hcnkpLCAtMiBiZWNvbWVzIDUgKDEwMSBiaW5hcnkpXG4gKi9cbmZ1bmN0aW9uIHRvVkxRU2lnbmVkKGFWYWx1ZSkge1xuICByZXR1cm4gYVZhbHVlIDwgMFxuICAgID8gKCgtYVZhbHVlKSA8PCAxKSArIDFcbiAgICA6IChhVmFsdWUgPDwgMSkgKyAwO1xufVxuXG4vKipcbiAqIENvbnZlcnRzIHRvIGEgdHdvLWNvbXBsZW1lbnQgdmFsdWUgZnJvbSBhIHZhbHVlIHdoZXJlIHRoZSBzaWduIGJpdCBpc1xuICogcGxhY2VkIGluIHRoZSBsZWFzdCBzaWduaWZpY2FudCBiaXQuICBGb3IgZXhhbXBsZSwgYXMgZGVjaW1hbHM6XG4gKiAgIDIgKDEwIGJpbmFyeSkgYmVjb21lcyAxLCAzICgxMSBiaW5hcnkpIGJlY29tZXMgLTFcbiAqICAgNCAoMTAwIGJpbmFyeSkgYmVjb21lcyAyLCA1ICgxMDEgYmluYXJ5KSBiZWNvbWVzIC0yXG4gKi9cbmZ1bmN0aW9uIGZyb21WTFFTaWduZWQoYVZhbHVlKSB7XG4gIHZhciBpc05lZ2F0aXZlID0gKGFWYWx1ZSAmIDEpID09PSAxO1xuICB2YXIgc2hpZnRlZCA9IGFWYWx1ZSA+PiAxO1xuICByZXR1cm4gaXNOZWdhdGl2ZVxuICAgID8gLXNoaWZ0ZWRcbiAgICA6IHNoaWZ0ZWQ7XG59XG5cbi8qKlxuICogUmV0dXJucyB0aGUgYmFzZSA2NCBWTFEgZW5jb2RlZCB2YWx1ZS5cbiAqL1xuZXhwb3J0cy5lbmNvZGUgPSBmdW5jdGlvbiBiYXNlNjRWTFFfZW5jb2RlKGFWYWx1ZSkge1xuICB2YXIgZW5jb2RlZCA9IFwiXCI7XG4gIHZhciBkaWdpdDtcblxuICB2YXIgdmxxID0gdG9WTFFTaWduZWQoYVZhbHVlKTtcblxuICBkbyB7XG4gICAgZGlnaXQgPSB2bHEgJiBWTFFfQkFTRV9NQVNLO1xuICAgIHZscSA+Pj49IFZMUV9CQVNFX1NISUZUO1xuICAgIGlmICh2bHEgPiAwKSB7XG4gICAgICAvLyBUaGVyZSBhcmUgc3RpbGwgbW9yZSBkaWdpdHMgaW4gdGhpcyB2YWx1ZSwgc28gd2UgbXVzdCBtYWtlIHN1cmUgdGhlXG4gICAgICAvLyBjb250aW51YXRpb24gYml0IGlzIG1hcmtlZC5cbiAgICAgIGRpZ2l0IHw9IFZMUV9DT05USU5VQVRJT05fQklUO1xuICAgIH1cbiAgICBlbmNvZGVkICs9IGJhc2U2NC5lbmNvZGUoZGlnaXQpO1xuICB9IHdoaWxlICh2bHEgPiAwKTtcblxuICByZXR1cm4gZW5jb2RlZDtcbn07XG5cbi8qKlxuICogRGVjb2RlcyB0aGUgbmV4dCBiYXNlIDY0IFZMUSB2YWx1ZSBmcm9tIHRoZSBnaXZlbiBzdHJpbmcgYW5kIHJldHVybnMgdGhlXG4gKiB2YWx1ZSBhbmQgdGhlIHJlc3Qgb2YgdGhlIHN0cmluZyB2aWEgdGhlIG91dCBwYXJhbWV0ZXIuXG4gKi9cbmV4cG9ydHMuZGVjb2RlID0gZnVuY3Rpb24gYmFzZTY0VkxRX2RlY29kZShhU3RyLCBhSW5kZXgsIGFPdXRQYXJhbSkge1xuICB2YXIgc3RyTGVuID0gYVN0ci5sZW5ndGg7XG4gIHZhciByZXN1bHQgPSAwO1xuICB2YXIgc2hpZnQgPSAwO1xuICB2YXIgY29udGludWF0aW9uLCBkaWdpdDtcblxuICBkbyB7XG4gICAgaWYgKGFJbmRleCA+PSBzdHJMZW4pIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcihcIkV4cGVjdGVkIG1vcmUgZGlnaXRzIGluIGJhc2UgNjQgVkxRIHZhbHVlLlwiKTtcbiAgICB9XG5cbiAgICBkaWdpdCA9IGJhc2U2NC5kZWNvZGUoYVN0ci5jaGFyQ29kZUF0KGFJbmRleCsrKSk7XG4gICAgaWYgKGRpZ2l0ID09PSAtMSkge1xuICAgICAgdGhyb3cgbmV3IEVycm9yKFwiSW52YWxpZCBiYXNlNjQgZGlnaXQ6IFwiICsgYVN0ci5jaGFyQXQoYUluZGV4IC0gMSkpO1xuICAgIH1cblxuICAgIGNvbnRpbnVhdGlvbiA9ICEhKGRpZ2l0ICYgVkxRX0NPTlRJTlVBVElPTl9CSVQpO1xuICAgIGRpZ2l0ICY9IFZMUV9CQVNFX01BU0s7XG4gICAgcmVzdWx0ID0gcmVzdWx0ICsgKGRpZ2l0IDw8IHNoaWZ0KTtcbiAgICBzaGlmdCArPSBWTFFfQkFTRV9TSElGVDtcbiAgfSB3aGlsZSAoY29udGludWF0aW9uKTtcblxuICBhT3V0UGFyYW0udmFsdWUgPSBmcm9tVkxRU2lnbmVkKHJlc3VsdCk7XG4gIGFPdXRQYXJhbS5yZXN0ID0gYUluZGV4O1xufTtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL2Jhc2U2NC12bHEuanNcbi8vIG1vZHVsZSBpZCA9IDJcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgaW50VG9DaGFyTWFwID0gJ0FCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU2Nzg5Ky8nLnNwbGl0KCcnKTtcblxuLyoqXG4gKiBFbmNvZGUgYW4gaW50ZWdlciBpbiB0aGUgcmFuZ2Ugb2YgMCB0byA2MyB0byBhIHNpbmdsZSBiYXNlIDY0IGRpZ2l0LlxuICovXG5leHBvcnRzLmVuY29kZSA9IGZ1bmN0aW9uIChudW1iZXIpIHtcbiAgaWYgKDAgPD0gbnVtYmVyICYmIG51bWJlciA8IGludFRvQ2hhck1hcC5sZW5ndGgpIHtcbiAgICByZXR1cm4gaW50VG9DaGFyTWFwW251bWJlcl07XG4gIH1cbiAgdGhyb3cgbmV3IFR5cGVFcnJvcihcIk11c3QgYmUgYmV0d2VlbiAwIGFuZCA2MzogXCIgKyBudW1iZXIpO1xufTtcblxuLyoqXG4gKiBEZWNvZGUgYSBzaW5nbGUgYmFzZSA2NCBjaGFyYWN0ZXIgY29kZSBkaWdpdCB0byBhbiBpbnRlZ2VyLiBSZXR1cm5zIC0xIG9uXG4gKiBmYWlsdXJlLlxuICovXG5leHBvcnRzLmRlY29kZSA9IGZ1bmN0aW9uIChjaGFyQ29kZSkge1xuICB2YXIgYmlnQSA9IDY1OyAgICAgLy8gJ0EnXG4gIHZhciBiaWdaID0gOTA7ICAgICAvLyAnWidcblxuICB2YXIgbGl0dGxlQSA9IDk3OyAgLy8gJ2EnXG4gIHZhciBsaXR0bGVaID0gMTIyOyAvLyAneidcblxuICB2YXIgemVybyA9IDQ4OyAgICAgLy8gJzAnXG4gIHZhciBuaW5lID0gNTc7ICAgICAvLyAnOSdcblxuICB2YXIgcGx1cyA9IDQzOyAgICAgLy8gJysnXG4gIHZhciBzbGFzaCA9IDQ3OyAgICAvLyAnLydcblxuICB2YXIgbGl0dGxlT2Zmc2V0ID0gMjY7XG4gIHZhciBudW1iZXJPZmZzZXQgPSA1MjtcblxuICAvLyAwIC0gMjU6IEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaXG4gIGlmIChiaWdBIDw9IGNoYXJDb2RlICYmIGNoYXJDb2RlIDw9IGJpZ1opIHtcbiAgICByZXR1cm4gKGNoYXJDb2RlIC0gYmlnQSk7XG4gIH1cblxuICAvLyAyNiAtIDUxOiBhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5elxuICBpZiAobGl0dGxlQSA8PSBjaGFyQ29kZSAmJiBjaGFyQ29kZSA8PSBsaXR0bGVaKSB7XG4gICAgcmV0dXJuIChjaGFyQ29kZSAtIGxpdHRsZUEgKyBsaXR0bGVPZmZzZXQpO1xuICB9XG5cbiAgLy8gNTIgLSA2MTogMDEyMzQ1Njc4OVxuICBpZiAoemVybyA8PSBjaGFyQ29kZSAmJiBjaGFyQ29kZSA8PSBuaW5lKSB7XG4gICAgcmV0dXJuIChjaGFyQ29kZSAtIHplcm8gKyBudW1iZXJPZmZzZXQpO1xuICB9XG5cbiAgLy8gNjI6ICtcbiAgaWYgKGNoYXJDb2RlID09IHBsdXMpIHtcbiAgICByZXR1cm4gNjI7XG4gIH1cblxuICAvLyA2MzogL1xuICBpZiAoY2hhckNvZGUgPT0gc2xhc2gpIHtcbiAgICByZXR1cm4gNjM7XG4gIH1cblxuICAvLyBJbnZhbGlkIGJhc2U2NCBkaWdpdC5cbiAgcmV0dXJuIC0xO1xufTtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL2Jhc2U2NC5qc1xuLy8gbW9kdWxlIGlkID0gM1xuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbi8qKlxuICogVGhpcyBpcyBhIGhlbHBlciBmdW5jdGlvbiBmb3IgZ2V0dGluZyB2YWx1ZXMgZnJvbSBwYXJhbWV0ZXIvb3B0aW9uc1xuICogb2JqZWN0cy5cbiAqXG4gKiBAcGFyYW0gYXJncyBUaGUgb2JqZWN0IHdlIGFyZSBleHRyYWN0aW5nIHZhbHVlcyBmcm9tXG4gKiBAcGFyYW0gbmFtZSBUaGUgbmFtZSBvZiB0aGUgcHJvcGVydHkgd2UgYXJlIGdldHRpbmcuXG4gKiBAcGFyYW0gZGVmYXVsdFZhbHVlIEFuIG9wdGlvbmFsIHZhbHVlIHRvIHJldHVybiBpZiB0aGUgcHJvcGVydHkgaXMgbWlzc2luZ1xuICogZnJvbSB0aGUgb2JqZWN0LiBJZiB0aGlzIGlzIG5vdCBzcGVjaWZpZWQgYW5kIHRoZSBwcm9wZXJ0eSBpcyBtaXNzaW5nLCBhblxuICogZXJyb3Igd2lsbCBiZSB0aHJvd24uXG4gKi9cbmZ1bmN0aW9uIGdldEFyZyhhQXJncywgYU5hbWUsIGFEZWZhdWx0VmFsdWUpIHtcbiAgaWYgKGFOYW1lIGluIGFBcmdzKSB7XG4gICAgcmV0dXJuIGFBcmdzW2FOYW1lXTtcbiAgfSBlbHNlIGlmIChhcmd1bWVudHMubGVuZ3RoID09PSAzKSB7XG4gICAgcmV0dXJuIGFEZWZhdWx0VmFsdWU7XG4gIH0gZWxzZSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCdcIicgKyBhTmFtZSArICdcIiBpcyBhIHJlcXVpcmVkIGFyZ3VtZW50LicpO1xuICB9XG59XG5leHBvcnRzLmdldEFyZyA9IGdldEFyZztcblxudmFyIHVybFJlZ2V4cCA9IC9eKD86KFtcXHcrXFwtLl0rKTopP1xcL1xcLyg/OihcXHcrOlxcdyspQCk/KFtcXHcuLV0qKSg/OjooXFxkKykpPyguKikkLztcbnZhciBkYXRhVXJsUmVnZXhwID0gL15kYXRhOi4rXFwsLiskLztcblxuZnVuY3Rpb24gdXJsUGFyc2UoYVVybCkge1xuICB2YXIgbWF0Y2ggPSBhVXJsLm1hdGNoKHVybFJlZ2V4cCk7XG4gIGlmICghbWF0Y2gpIHtcbiAgICByZXR1cm4gbnVsbDtcbiAgfVxuICByZXR1cm4ge1xuICAgIHNjaGVtZTogbWF0Y2hbMV0sXG4gICAgYXV0aDogbWF0Y2hbMl0sXG4gICAgaG9zdDogbWF0Y2hbM10sXG4gICAgcG9ydDogbWF0Y2hbNF0sXG4gICAgcGF0aDogbWF0Y2hbNV1cbiAgfTtcbn1cbmV4cG9ydHMudXJsUGFyc2UgPSB1cmxQYXJzZTtcblxuZnVuY3Rpb24gdXJsR2VuZXJhdGUoYVBhcnNlZFVybCkge1xuICB2YXIgdXJsID0gJyc7XG4gIGlmIChhUGFyc2VkVXJsLnNjaGVtZSkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLnNjaGVtZSArICc6JztcbiAgfVxuICB1cmwgKz0gJy8vJztcbiAgaWYgKGFQYXJzZWRVcmwuYXV0aCkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLmF1dGggKyAnQCc7XG4gIH1cbiAgaWYgKGFQYXJzZWRVcmwuaG9zdCkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLmhvc3Q7XG4gIH1cbiAgaWYgKGFQYXJzZWRVcmwucG9ydCkge1xuICAgIHVybCArPSBcIjpcIiArIGFQYXJzZWRVcmwucG9ydFxuICB9XG4gIGlmIChhUGFyc2VkVXJsLnBhdGgpIHtcbiAgICB1cmwgKz0gYVBhcnNlZFVybC5wYXRoO1xuICB9XG4gIHJldHVybiB1cmw7XG59XG5leHBvcnRzLnVybEdlbmVyYXRlID0gdXJsR2VuZXJhdGU7XG5cbi8qKlxuICogTm9ybWFsaXplcyBhIHBhdGgsIG9yIHRoZSBwYXRoIHBvcnRpb24gb2YgYSBVUkw6XG4gKlxuICogLSBSZXBsYWNlcyBjb25zZWN1dGl2ZSBzbGFzaGVzIHdpdGggb25lIHNsYXNoLlxuICogLSBSZW1vdmVzIHVubmVjZXNzYXJ5ICcuJyBwYXJ0cy5cbiAqIC0gUmVtb3ZlcyB1bm5lY2Vzc2FyeSAnPGRpcj4vLi4nIHBhcnRzLlxuICpcbiAqIEJhc2VkIG9uIGNvZGUgaW4gdGhlIE5vZGUuanMgJ3BhdGgnIGNvcmUgbW9kdWxlLlxuICpcbiAqIEBwYXJhbSBhUGF0aCBUaGUgcGF0aCBvciB1cmwgdG8gbm9ybWFsaXplLlxuICovXG5mdW5jdGlvbiBub3JtYWxpemUoYVBhdGgpIHtcbiAgdmFyIHBhdGggPSBhUGF0aDtcbiAgdmFyIHVybCA9IHVybFBhcnNlKGFQYXRoKTtcbiAgaWYgKHVybCkge1xuICAgIGlmICghdXJsLnBhdGgpIHtcbiAgICAgIHJldHVybiBhUGF0aDtcbiAgICB9XG4gICAgcGF0aCA9IHVybC5wYXRoO1xuICB9XG4gIHZhciBpc0Fic29sdXRlID0gZXhwb3J0cy5pc0Fic29sdXRlKHBhdGgpO1xuXG4gIHZhciBwYXJ0cyA9IHBhdGguc3BsaXQoL1xcLysvKTtcbiAgZm9yICh2YXIgcGFydCwgdXAgPSAwLCBpID0gcGFydHMubGVuZ3RoIC0gMTsgaSA+PSAwOyBpLS0pIHtcbiAgICBwYXJ0ID0gcGFydHNbaV07XG4gICAgaWYgKHBhcnQgPT09ICcuJykge1xuICAgICAgcGFydHMuc3BsaWNlKGksIDEpO1xuICAgIH0gZWxzZSBpZiAocGFydCA9PT0gJy4uJykge1xuICAgICAgdXArKztcbiAgICB9IGVsc2UgaWYgKHVwID4gMCkge1xuICAgICAgaWYgKHBhcnQgPT09ICcnKSB7XG4gICAgICAgIC8vIFRoZSBmaXJzdCBwYXJ0IGlzIGJsYW5rIGlmIHRoZSBwYXRoIGlzIGFic29sdXRlLiBUcnlpbmcgdG8gZ29cbiAgICAgICAgLy8gYWJvdmUgdGhlIHJvb3QgaXMgYSBuby1vcC4gVGhlcmVmb3JlIHdlIGNhbiByZW1vdmUgYWxsICcuLicgcGFydHNcbiAgICAgICAgLy8gZGlyZWN0bHkgYWZ0ZXIgdGhlIHJvb3QuXG4gICAgICAgIHBhcnRzLnNwbGljZShpICsgMSwgdXApO1xuICAgICAgICB1cCA9IDA7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBwYXJ0cy5zcGxpY2UoaSwgMik7XG4gICAgICAgIHVwLS07XG4gICAgICB9XG4gICAgfVxuICB9XG4gIHBhdGggPSBwYXJ0cy5qb2luKCcvJyk7XG5cbiAgaWYgKHBhdGggPT09ICcnKSB7XG4gICAgcGF0aCA9IGlzQWJzb2x1dGUgPyAnLycgOiAnLic7XG4gIH1cblxuICBpZiAodXJsKSB7XG4gICAgdXJsLnBhdGggPSBwYXRoO1xuICAgIHJldHVybiB1cmxHZW5lcmF0ZSh1cmwpO1xuICB9XG4gIHJldHVybiBwYXRoO1xufVxuZXhwb3J0cy5ub3JtYWxpemUgPSBub3JtYWxpemU7XG5cbi8qKlxuICogSm9pbnMgdHdvIHBhdGhzL1VSTHMuXG4gKlxuICogQHBhcmFtIGFSb290IFRoZSByb290IHBhdGggb3IgVVJMLlxuICogQHBhcmFtIGFQYXRoIFRoZSBwYXRoIG9yIFVSTCB0byBiZSBqb2luZWQgd2l0aCB0aGUgcm9vdC5cbiAqXG4gKiAtIElmIGFQYXRoIGlzIGEgVVJMIG9yIGEgZGF0YSBVUkksIGFQYXRoIGlzIHJldHVybmVkLCB1bmxlc3MgYVBhdGggaXMgYVxuICogICBzY2hlbWUtcmVsYXRpdmUgVVJMOiBUaGVuIHRoZSBzY2hlbWUgb2YgYVJvb3QsIGlmIGFueSwgaXMgcHJlcGVuZGVkXG4gKiAgIGZpcnN0LlxuICogLSBPdGhlcndpc2UgYVBhdGggaXMgYSBwYXRoLiBJZiBhUm9vdCBpcyBhIFVSTCwgdGhlbiBpdHMgcGF0aCBwb3J0aW9uXG4gKiAgIGlzIHVwZGF0ZWQgd2l0aCB0aGUgcmVzdWx0IGFuZCBhUm9vdCBpcyByZXR1cm5lZC4gT3RoZXJ3aXNlIHRoZSByZXN1bHRcbiAqICAgaXMgcmV0dXJuZWQuXG4gKiAgIC0gSWYgYVBhdGggaXMgYWJzb2x1dGUsIHRoZSByZXN1bHQgaXMgYVBhdGguXG4gKiAgIC0gT3RoZXJ3aXNlIHRoZSB0d28gcGF0aHMgYXJlIGpvaW5lZCB3aXRoIGEgc2xhc2guXG4gKiAtIEpvaW5pbmcgZm9yIGV4YW1wbGUgJ2h0dHA6Ly8nIGFuZCAnd3d3LmV4YW1wbGUuY29tJyBpcyBhbHNvIHN1cHBvcnRlZC5cbiAqL1xuZnVuY3Rpb24gam9pbihhUm9vdCwgYVBhdGgpIHtcbiAgaWYgKGFSb290ID09PSBcIlwiKSB7XG4gICAgYVJvb3QgPSBcIi5cIjtcbiAgfVxuICBpZiAoYVBhdGggPT09IFwiXCIpIHtcbiAgICBhUGF0aCA9IFwiLlwiO1xuICB9XG4gIHZhciBhUGF0aFVybCA9IHVybFBhcnNlKGFQYXRoKTtcbiAgdmFyIGFSb290VXJsID0gdXJsUGFyc2UoYVJvb3QpO1xuICBpZiAoYVJvb3RVcmwpIHtcbiAgICBhUm9vdCA9IGFSb290VXJsLnBhdGggfHwgJy8nO1xuICB9XG5cbiAgLy8gYGpvaW4oZm9vLCAnLy93d3cuZXhhbXBsZS5vcmcnKWBcbiAgaWYgKGFQYXRoVXJsICYmICFhUGF0aFVybC5zY2hlbWUpIHtcbiAgICBpZiAoYVJvb3RVcmwpIHtcbiAgICAgIGFQYXRoVXJsLnNjaGVtZSA9IGFSb290VXJsLnNjaGVtZTtcbiAgICB9XG4gICAgcmV0dXJuIHVybEdlbmVyYXRlKGFQYXRoVXJsKTtcbiAgfVxuXG4gIGlmIChhUGF0aFVybCB8fCBhUGF0aC5tYXRjaChkYXRhVXJsUmVnZXhwKSkge1xuICAgIHJldHVybiBhUGF0aDtcbiAgfVxuXG4gIC8vIGBqb2luKCdodHRwOi8vJywgJ3d3dy5leGFtcGxlLmNvbScpYFxuICBpZiAoYVJvb3RVcmwgJiYgIWFSb290VXJsLmhvc3QgJiYgIWFSb290VXJsLnBhdGgpIHtcbiAgICBhUm9vdFVybC5ob3N0ID0gYVBhdGg7XG4gICAgcmV0dXJuIHVybEdlbmVyYXRlKGFSb290VXJsKTtcbiAgfVxuXG4gIHZhciBqb2luZWQgPSBhUGF0aC5jaGFyQXQoMCkgPT09ICcvJ1xuICAgID8gYVBhdGhcbiAgICA6IG5vcm1hbGl6ZShhUm9vdC5yZXBsYWNlKC9cXC8rJC8sICcnKSArICcvJyArIGFQYXRoKTtcblxuICBpZiAoYVJvb3RVcmwpIHtcbiAgICBhUm9vdFVybC5wYXRoID0gam9pbmVkO1xuICAgIHJldHVybiB1cmxHZW5lcmF0ZShhUm9vdFVybCk7XG4gIH1cbiAgcmV0dXJuIGpvaW5lZDtcbn1cbmV4cG9ydHMuam9pbiA9IGpvaW47XG5cbmV4cG9ydHMuaXNBYnNvbHV0ZSA9IGZ1bmN0aW9uIChhUGF0aCkge1xuICByZXR1cm4gYVBhdGguY2hhckF0KDApID09PSAnLycgfHwgdXJsUmVnZXhwLnRlc3QoYVBhdGgpO1xufTtcblxuLyoqXG4gKiBNYWtlIGEgcGF0aCByZWxhdGl2ZSB0byBhIFVSTCBvciBhbm90aGVyIHBhdGguXG4gKlxuICogQHBhcmFtIGFSb290IFRoZSByb290IHBhdGggb3IgVVJMLlxuICogQHBhcmFtIGFQYXRoIFRoZSBwYXRoIG9yIFVSTCB0byBiZSBtYWRlIHJlbGF0aXZlIHRvIGFSb290LlxuICovXG5mdW5jdGlvbiByZWxhdGl2ZShhUm9vdCwgYVBhdGgpIHtcbiAgaWYgKGFSb290ID09PSBcIlwiKSB7XG4gICAgYVJvb3QgPSBcIi5cIjtcbiAgfVxuXG4gIGFSb290ID0gYVJvb3QucmVwbGFjZSgvXFwvJC8sICcnKTtcblxuICAvLyBJdCBpcyBwb3NzaWJsZSBmb3IgdGhlIHBhdGggdG8gYmUgYWJvdmUgdGhlIHJvb3QuIEluIHRoaXMgY2FzZSwgc2ltcGx5XG4gIC8vIGNoZWNraW5nIHdoZXRoZXIgdGhlIHJvb3QgaXMgYSBwcmVmaXggb2YgdGhlIHBhdGggd29uJ3Qgd29yay4gSW5zdGVhZCwgd2VcbiAgLy8gbmVlZCB0byByZW1vdmUgY29tcG9uZW50cyBmcm9tIHRoZSByb290IG9uZSBieSBvbmUsIHVudGlsIGVpdGhlciB3ZSBmaW5kXG4gIC8vIGEgcHJlZml4IHRoYXQgZml0cywgb3Igd2UgcnVuIG91dCBvZiBjb21wb25lbnRzIHRvIHJlbW92ZS5cbiAgdmFyIGxldmVsID0gMDtcbiAgd2hpbGUgKGFQYXRoLmluZGV4T2YoYVJvb3QgKyAnLycpICE9PSAwKSB7XG4gICAgdmFyIGluZGV4ID0gYVJvb3QubGFzdEluZGV4T2YoXCIvXCIpO1xuICAgIGlmIChpbmRleCA8IDApIHtcbiAgICAgIHJldHVybiBhUGF0aDtcbiAgICB9XG5cbiAgICAvLyBJZiB0aGUgb25seSBwYXJ0IG9mIHRoZSByb290IHRoYXQgaXMgbGVmdCBpcyB0aGUgc2NoZW1lIChpLmUuIGh0dHA6Ly8sXG4gICAgLy8gZmlsZTovLy8sIGV0Yy4pLCBvbmUgb3IgbW9yZSBzbGFzaGVzICgvKSwgb3Igc2ltcGx5IG5vdGhpbmcgYXQgYWxsLCB3ZVxuICAgIC8vIGhhdmUgZXhoYXVzdGVkIGFsbCBjb21wb25lbnRzLCBzbyB0aGUgcGF0aCBpcyBub3QgcmVsYXRpdmUgdG8gdGhlIHJvb3QuXG4gICAgYVJvb3QgPSBhUm9vdC5zbGljZSgwLCBpbmRleCk7XG4gICAgaWYgKGFSb290Lm1hdGNoKC9eKFteXFwvXSs6XFwvKT9cXC8qJC8pKSB7XG4gICAgICByZXR1cm4gYVBhdGg7XG4gICAgfVxuXG4gICAgKytsZXZlbDtcbiAgfVxuXG4gIC8vIE1ha2Ugc3VyZSB3ZSBhZGQgYSBcIi4uL1wiIGZvciBlYWNoIGNvbXBvbmVudCB3ZSByZW1vdmVkIGZyb20gdGhlIHJvb3QuXG4gIHJldHVybiBBcnJheShsZXZlbCArIDEpLmpvaW4oXCIuLi9cIikgKyBhUGF0aC5zdWJzdHIoYVJvb3QubGVuZ3RoICsgMSk7XG59XG5leHBvcnRzLnJlbGF0aXZlID0gcmVsYXRpdmU7XG5cbnZhciBzdXBwb3J0c051bGxQcm90byA9IChmdW5jdGlvbiAoKSB7XG4gIHZhciBvYmogPSBPYmplY3QuY3JlYXRlKG51bGwpO1xuICByZXR1cm4gISgnX19wcm90b19fJyBpbiBvYmopO1xufSgpKTtcblxuZnVuY3Rpb24gaWRlbnRpdHkgKHMpIHtcbiAgcmV0dXJuIHM7XG59XG5cbi8qKlxuICogQmVjYXVzZSBiZWhhdmlvciBnb2VzIHdhY2t5IHdoZW4geW91IHNldCBgX19wcm90b19fYCBvbiBvYmplY3RzLCB3ZVxuICogaGF2ZSB0byBwcmVmaXggYWxsIHRoZSBzdHJpbmdzIGluIG91ciBzZXQgd2l0aCBhbiBhcmJpdHJhcnkgY2hhcmFjdGVyLlxuICpcbiAqIFNlZSBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL3B1bGwvMzEgYW5kXG4gKiBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL2lzc3Vlcy8zMFxuICpcbiAqIEBwYXJhbSBTdHJpbmcgYVN0clxuICovXG5mdW5jdGlvbiB0b1NldFN0cmluZyhhU3RyKSB7XG4gIGlmIChpc1Byb3RvU3RyaW5nKGFTdHIpKSB7XG4gICAgcmV0dXJuICckJyArIGFTdHI7XG4gIH1cblxuICByZXR1cm4gYVN0cjtcbn1cbmV4cG9ydHMudG9TZXRTdHJpbmcgPSBzdXBwb3J0c051bGxQcm90byA/IGlkZW50aXR5IDogdG9TZXRTdHJpbmc7XG5cbmZ1bmN0aW9uIGZyb21TZXRTdHJpbmcoYVN0cikge1xuICBpZiAoaXNQcm90b1N0cmluZyhhU3RyKSkge1xuICAgIHJldHVybiBhU3RyLnNsaWNlKDEpO1xuICB9XG5cbiAgcmV0dXJuIGFTdHI7XG59XG5leHBvcnRzLmZyb21TZXRTdHJpbmcgPSBzdXBwb3J0c051bGxQcm90byA/IGlkZW50aXR5IDogZnJvbVNldFN0cmluZztcblxuZnVuY3Rpb24gaXNQcm90b1N0cmluZyhzKSB7XG4gIGlmICghcykge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIHZhciBsZW5ndGggPSBzLmxlbmd0aDtcblxuICBpZiAobGVuZ3RoIDwgOSAvKiBcIl9fcHJvdG9fX1wiLmxlbmd0aCAqLykge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIGlmIChzLmNoYXJDb2RlQXQobGVuZ3RoIC0gMSkgIT09IDk1ICAvKiAnXycgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSAyKSAhPT0gOTUgIC8qICdfJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDMpICE9PSAxMTEgLyogJ28nICovIHx8XG4gICAgICBzLmNoYXJDb2RlQXQobGVuZ3RoIC0gNCkgIT09IDExNiAvKiAndCcgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSA1KSAhPT0gMTExIC8qICdvJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDYpICE9PSAxMTQgLyogJ3InICovIHx8XG4gICAgICBzLmNoYXJDb2RlQXQobGVuZ3RoIC0gNykgIT09IDExMiAvKiAncCcgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSA4KSAhPT0gOTUgIC8qICdfJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDkpICE9PSA5NSAgLyogJ18nICovKSB7XG4gICAgcmV0dXJuIGZhbHNlO1xuICB9XG5cbiAgZm9yICh2YXIgaSA9IGxlbmd0aCAtIDEwOyBpID49IDA7IGktLSkge1xuICAgIGlmIChzLmNoYXJDb2RlQXQoaSkgIT09IDM2IC8qICckJyAqLykge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB0cnVlO1xufVxuXG4vKipcbiAqIENvbXBhcmF0b3IgYmV0d2VlbiB0d28gbWFwcGluZ3Mgd2hlcmUgdGhlIG9yaWdpbmFsIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKlxuICogT3B0aW9uYWxseSBwYXNzIGluIGB0cnVlYCBhcyBgb25seUNvbXBhcmVHZW5lcmF0ZWRgIHRvIGNvbnNpZGVyIHR3b1xuICogbWFwcGluZ3Mgd2l0aCB0aGUgc2FtZSBvcmlnaW5hbCBzb3VyY2UvbGluZS9jb2x1bW4sIGJ1dCBkaWZmZXJlbnQgZ2VuZXJhdGVkXG4gKiBsaW5lIGFuZCBjb2x1bW4gdGhlIHNhbWUuIFVzZWZ1bCB3aGVuIHNlYXJjaGluZyBmb3IgYSBtYXBwaW5nIHdpdGggYVxuICogc3R1YmJlZCBvdXQgbWFwcGluZy5cbiAqL1xuZnVuY3Rpb24gY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMobWFwcGluZ0EsIG1hcHBpbmdCLCBvbmx5Q29tcGFyZU9yaWdpbmFsKSB7XG4gIHZhciBjbXAgPSBzdHJjbXAobWFwcGluZ0Euc291cmNlLCBtYXBwaW5nQi5zb3VyY2UpO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsTGluZSAtIG1hcHBpbmdCLm9yaWdpbmFsTGluZTtcbiAgaWYgKGNtcCAhPT0gMCkge1xuICAgIHJldHVybiBjbXA7XG4gIH1cblxuICBjbXAgPSBtYXBwaW5nQS5vcmlnaW5hbENvbHVtbiAtIG1hcHBpbmdCLm9yaWdpbmFsQ29sdW1uO1xuICBpZiAoY21wICE9PSAwIHx8IG9ubHlDb21wYXJlT3JpZ2luYWwpIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkQ29sdW1uIC0gbWFwcGluZ0IuZ2VuZXJhdGVkQ29sdW1uO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLmdlbmVyYXRlZExpbmUgLSBtYXBwaW5nQi5nZW5lcmF0ZWRMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIHJldHVybiBzdHJjbXAobWFwcGluZ0EubmFtZSwgbWFwcGluZ0IubmFtZSk7XG59XG5leHBvcnRzLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zID0gY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnM7XG5cbi8qKlxuICogQ29tcGFyYXRvciBiZXR3ZWVuIHR3byBtYXBwaW5ncyB3aXRoIGRlZmxhdGVkIHNvdXJjZSBhbmQgbmFtZSBpbmRpY2VzIHdoZXJlXG4gKiB0aGUgZ2VuZXJhdGVkIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKlxuICogT3B0aW9uYWxseSBwYXNzIGluIGB0cnVlYCBhcyBgb25seUNvbXBhcmVHZW5lcmF0ZWRgIHRvIGNvbnNpZGVyIHR3b1xuICogbWFwcGluZ3Mgd2l0aCB0aGUgc2FtZSBnZW5lcmF0ZWQgbGluZSBhbmQgY29sdW1uLCBidXQgZGlmZmVyZW50XG4gKiBzb3VyY2UvbmFtZS9vcmlnaW5hbCBsaW5lIGFuZCBjb2x1bW4gdGhlIHNhbWUuIFVzZWZ1bCB3aGVuIHNlYXJjaGluZyBmb3IgYVxuICogbWFwcGluZyB3aXRoIGEgc3R1YmJlZCBvdXQgbWFwcGluZy5cbiAqL1xuZnVuY3Rpb24gY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zRGVmbGF0ZWQobWFwcGluZ0EsIG1hcHBpbmdCLCBvbmx5Q29tcGFyZUdlbmVyYXRlZCkge1xuICB2YXIgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkTGluZSAtIG1hcHBpbmdCLmdlbmVyYXRlZExpbmU7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkQ29sdW1uIC0gbWFwcGluZ0IuZ2VuZXJhdGVkQ29sdW1uO1xuICBpZiAoY21wICE9PSAwIHx8IG9ubHlDb21wYXJlR2VuZXJhdGVkKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IHN0cmNtcChtYXBwaW5nQS5zb3VyY2UsIG1hcHBpbmdCLnNvdXJjZSk7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0Eub3JpZ2luYWxMaW5lIC0gbWFwcGluZ0Iub3JpZ2luYWxMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsQ29sdW1uIC0gbWFwcGluZ0Iub3JpZ2luYWxDb2x1bW47XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgcmV0dXJuIHN0cmNtcChtYXBwaW5nQS5uYW1lLCBtYXBwaW5nQi5uYW1lKTtcbn1cbmV4cG9ydHMuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zRGVmbGF0ZWQgPSBjb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNEZWZsYXRlZDtcblxuZnVuY3Rpb24gc3RyY21wKGFTdHIxLCBhU3RyMikge1xuICBpZiAoYVN0cjEgPT09IGFTdHIyKSB7XG4gICAgcmV0dXJuIDA7XG4gIH1cblxuICBpZiAoYVN0cjEgPT09IG51bGwpIHtcbiAgICByZXR1cm4gMTsgLy8gYVN0cjIgIT09IG51bGxcbiAgfVxuXG4gIGlmIChhU3RyMiA9PT0gbnVsbCkge1xuICAgIHJldHVybiAtMTsgLy8gYVN0cjEgIT09IG51bGxcbiAgfVxuXG4gIGlmIChhU3RyMSA+IGFTdHIyKSB7XG4gICAgcmV0dXJuIDE7XG4gIH1cblxuICByZXR1cm4gLTE7XG59XG5cbi8qKlxuICogQ29tcGFyYXRvciBiZXR3ZWVuIHR3byBtYXBwaW5ncyB3aXRoIGluZmxhdGVkIHNvdXJjZSBhbmQgbmFtZSBzdHJpbmdzIHdoZXJlXG4gKiB0aGUgZ2VuZXJhdGVkIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKi9cbmZ1bmN0aW9uIGNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0luZmxhdGVkKG1hcHBpbmdBLCBtYXBwaW5nQikge1xuICB2YXIgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkTGluZSAtIG1hcHBpbmdCLmdlbmVyYXRlZExpbmU7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkQ29sdW1uIC0gbWFwcGluZ0IuZ2VuZXJhdGVkQ29sdW1uO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IHN0cmNtcChtYXBwaW5nQS5zb3VyY2UsIG1hcHBpbmdCLnNvdXJjZSk7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0Eub3JpZ2luYWxMaW5lIC0gbWFwcGluZ0Iub3JpZ2luYWxMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsQ29sdW1uIC0gbWFwcGluZ0Iub3JpZ2luYWxDb2x1bW47XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgcmV0dXJuIHN0cmNtcChtYXBwaW5nQS5uYW1lLCBtYXBwaW5nQi5uYW1lKTtcbn1cbmV4cG9ydHMuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zSW5mbGF0ZWQgPSBjb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZDtcblxuLyoqXG4gKiBTdHJpcCBhbnkgSlNPTiBYU1NJIGF2b2lkYW5jZSBwcmVmaXggZnJvbSB0aGUgc3RyaW5nIChhcyBkb2N1bWVudGVkXG4gKiBpbiB0aGUgc291cmNlIG1hcHMgc3BlY2lmaWNhdGlvbiksIGFuZCB0aGVuIHBhcnNlIHRoZSBzdHJpbmcgYXNcbiAqIEpTT04uXG4gKi9cbmZ1bmN0aW9uIHBhcnNlU291cmNlTWFwSW5wdXQoc3RyKSB7XG4gIHJldHVybiBKU09OLnBhcnNlKHN0ci5yZXBsYWNlKC9eXFwpXX0nW15cXG5dKlxcbi8sICcnKSk7XG59XG5leHBvcnRzLnBhcnNlU291cmNlTWFwSW5wdXQgPSBwYXJzZVNvdXJjZU1hcElucHV0O1xuXG4vKipcbiAqIENvbXB1dGUgdGhlIFVSTCBvZiBhIHNvdXJjZSBnaXZlbiB0aGUgdGhlIHNvdXJjZSByb290LCB0aGUgc291cmNlJ3NcbiAqIFVSTCwgYW5kIHRoZSBzb3VyY2UgbWFwJ3MgVVJMLlxuICovXG5mdW5jdGlvbiBjb21wdXRlU291cmNlVVJMKHNvdXJjZVJvb3QsIHNvdXJjZVVSTCwgc291cmNlTWFwVVJMKSB7XG4gIHNvdXJjZVVSTCA9IHNvdXJjZVVSTCB8fCAnJztcblxuICBpZiAoc291cmNlUm9vdCkge1xuICAgIC8vIFRoaXMgZm9sbG93cyB3aGF0IENocm9tZSBkb2VzLlxuICAgIGlmIChzb3VyY2VSb290W3NvdXJjZVJvb3QubGVuZ3RoIC0gMV0gIT09ICcvJyAmJiBzb3VyY2VVUkxbMF0gIT09ICcvJykge1xuICAgICAgc291cmNlUm9vdCArPSAnLyc7XG4gICAgfVxuICAgIC8vIFRoZSBzcGVjIHNheXM6XG4gICAgLy8gICBMaW5lIDQ6IEFuIG9wdGlvbmFsIHNvdXJjZSByb290LCB1c2VmdWwgZm9yIHJlbG9jYXRpbmcgc291cmNlXG4gICAgLy8gICBmaWxlcyBvbiBhIHNlcnZlciBvciByZW1vdmluZyByZXBlYXRlZCB2YWx1ZXMgaW4gdGhlXG4gICAgLy8gICDigJxzb3VyY2Vz4oCdIGVudHJ5LiAgVGhpcyB2YWx1ZSBpcyBwcmVwZW5kZWQgdG8gdGhlIGluZGl2aWR1YWxcbiAgICAvLyAgIGVudHJpZXMgaW4gdGhlIOKAnHNvdXJjZeKAnSBmaWVsZC5cbiAgICBzb3VyY2VVUkwgPSBzb3VyY2VSb290ICsgc291cmNlVVJMO1xuICB9XG5cbiAgLy8gSGlzdG9yaWNhbGx5LCBTb3VyY2VNYXBDb25zdW1lciBkaWQgbm90IHRha2UgdGhlIHNvdXJjZU1hcFVSTCBhc1xuICAvLyBhIHBhcmFtZXRlci4gIFRoaXMgbW9kZSBpcyBzdGlsbCBzb21ld2hhdCBzdXBwb3J0ZWQsIHdoaWNoIGlzIHdoeVxuICAvLyB0aGlzIGNvZGUgYmxvY2sgaXMgY29uZGl0aW9uYWwuICBIb3dldmVyLCBpdCdzIHByZWZlcmFibGUgdG8gcGFzc1xuICAvLyB0aGUgc291cmNlIG1hcCBVUkwgdG8gU291cmNlTWFwQ29uc3VtZXIsIHNvIHRoYXQgdGhpcyBmdW5jdGlvblxuICAvLyBjYW4gaW1wbGVtZW50IHRoZSBzb3VyY2UgVVJMIHJlc29sdXRpb24gYWxnb3JpdGhtIGFzIG91dGxpbmVkIGluXG4gIC8vIHRoZSBzcGVjLiAgVGhpcyBibG9jayBpcyBiYXNpY2FsbHkgdGhlIGVxdWl2YWxlbnQgb2Y6XG4gIC8vICAgIG5ldyBVUkwoc291cmNlVVJMLCBzb3VyY2VNYXBVUkwpLnRvU3RyaW5nKClcbiAgLy8gLi4uIGV4Y2VwdCBpdCBhdm9pZHMgdXNpbmcgVVJMLCB3aGljaCB3YXNuJ3QgYXZhaWxhYmxlIGluIHRoZVxuICAvLyBvbGRlciByZWxlYXNlcyBvZiBub2RlIHN0aWxsIHN1cHBvcnRlZCBieSB0aGlzIGxpYnJhcnkuXG4gIC8vXG4gIC8vIFRoZSBzcGVjIHNheXM6XG4gIC8vICAgSWYgdGhlIHNvdXJjZXMgYXJlIG5vdCBhYnNvbHV0ZSBVUkxzIGFmdGVyIHByZXBlbmRpbmcgb2YgdGhlXG4gIC8vICAg4oCcc291cmNlUm9vdOKAnSwgdGhlIHNvdXJjZXMgYXJlIHJlc29sdmVkIHJlbGF0aXZlIHRvIHRoZVxuICAvLyAgIFNvdXJjZU1hcCAobGlrZSByZXNvbHZpbmcgc2NyaXB0IHNyYyBpbiBhIGh0bWwgZG9jdW1lbnQpLlxuICBpZiAoc291cmNlTWFwVVJMKSB7XG4gICAgdmFyIHBhcnNlZCA9IHVybFBhcnNlKHNvdXJjZU1hcFVSTCk7XG4gICAgaWYgKCFwYXJzZWQpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcihcInNvdXJjZU1hcFVSTCBjb3VsZCBub3QgYmUgcGFyc2VkXCIpO1xuICAgIH1cbiAgICBpZiAocGFyc2VkLnBhdGgpIHtcbiAgICAgIC8vIFN0cmlwIHRoZSBsYXN0IHBhdGggY29tcG9uZW50LCBidXQga2VlcCB0aGUgXCIvXCIuXG4gICAgICB2YXIgaW5kZXggPSBwYXJzZWQucGF0aC5sYXN0SW5kZXhPZignLycpO1xuICAgICAgaWYgKGluZGV4ID49IDApIHtcbiAgICAgICAgcGFyc2VkLnBhdGggPSBwYXJzZWQucGF0aC5zdWJzdHJpbmcoMCwgaW5kZXggKyAxKTtcbiAgICAgIH1cbiAgICB9XG4gICAgc291cmNlVVJMID0gam9pbih1cmxHZW5lcmF0ZShwYXJzZWQpLCBzb3VyY2VVUkwpO1xuICB9XG5cbiAgcmV0dXJuIG5vcm1hbGl6ZShzb3VyY2VVUkwpO1xufVxuZXhwb3J0cy5jb21wdXRlU291cmNlVVJMID0gY29tcHV0ZVNvdXJjZVVSTDtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL3V0aWwuanNcbi8vIG1vZHVsZSBpZCA9IDRcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgdXRpbCA9IHJlcXVpcmUoJy4vdXRpbCcpO1xudmFyIGhhcyA9IE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHk7XG52YXIgaGFzTmF0aXZlTWFwID0gdHlwZW9mIE1hcCAhPT0gXCJ1bmRlZmluZWRcIjtcblxuLyoqXG4gKiBBIGRhdGEgc3RydWN0dXJlIHdoaWNoIGlzIGEgY29tYmluYXRpb24gb2YgYW4gYXJyYXkgYW5kIGEgc2V0LiBBZGRpbmcgYSBuZXdcbiAqIG1lbWJlciBpcyBPKDEpLCB0ZXN0aW5nIGZvciBtZW1iZXJzaGlwIGlzIE8oMSksIGFuZCBmaW5kaW5nIHRoZSBpbmRleCBvZiBhblxuICogZWxlbWVudCBpcyBPKDEpLiBSZW1vdmluZyBlbGVtZW50cyBmcm9tIHRoZSBzZXQgaXMgbm90IHN1cHBvcnRlZC4gT25seVxuICogc3RyaW5ncyBhcmUgc3VwcG9ydGVkIGZvciBtZW1iZXJzaGlwLlxuICovXG5mdW5jdGlvbiBBcnJheVNldCgpIHtcbiAgdGhpcy5fYXJyYXkgPSBbXTtcbiAgdGhpcy5fc2V0ID0gaGFzTmF0aXZlTWFwID8gbmV3IE1hcCgpIDogT2JqZWN0LmNyZWF0ZShudWxsKTtcbn1cblxuLyoqXG4gKiBTdGF0aWMgbWV0aG9kIGZvciBjcmVhdGluZyBBcnJheVNldCBpbnN0YW5jZXMgZnJvbSBhbiBleGlzdGluZyBhcnJheS5cbiAqL1xuQXJyYXlTZXQuZnJvbUFycmF5ID0gZnVuY3Rpb24gQXJyYXlTZXRfZnJvbUFycmF5KGFBcnJheSwgYUFsbG93RHVwbGljYXRlcykge1xuICB2YXIgc2V0ID0gbmV3IEFycmF5U2V0KCk7XG4gIGZvciAodmFyIGkgPSAwLCBsZW4gPSBhQXJyYXkubGVuZ3RoOyBpIDwgbGVuOyBpKyspIHtcbiAgICBzZXQuYWRkKGFBcnJheVtpXSwgYUFsbG93RHVwbGljYXRlcyk7XG4gIH1cbiAgcmV0dXJuIHNldDtcbn07XG5cbi8qKlxuICogUmV0dXJuIGhvdyBtYW55IHVuaXF1ZSBpdGVtcyBhcmUgaW4gdGhpcyBBcnJheVNldC4gSWYgZHVwbGljYXRlcyBoYXZlIGJlZW5cbiAqIGFkZGVkLCB0aGFuIHRob3NlIGRvIG5vdCBjb3VudCB0b3dhcmRzIHRoZSBzaXplLlxuICpcbiAqIEByZXR1cm5zIE51bWJlclxuICovXG5BcnJheVNldC5wcm90b3R5cGUuc2l6ZSA9IGZ1bmN0aW9uIEFycmF5U2V0X3NpemUoKSB7XG4gIHJldHVybiBoYXNOYXRpdmVNYXAgPyB0aGlzLl9zZXQuc2l6ZSA6IE9iamVjdC5nZXRPd25Qcm9wZXJ0eU5hbWVzKHRoaXMuX3NldCkubGVuZ3RoO1xufTtcblxuLyoqXG4gKiBBZGQgdGhlIGdpdmVuIHN0cmluZyB0byB0aGlzIHNldC5cbiAqXG4gKiBAcGFyYW0gU3RyaW5nIGFTdHJcbiAqL1xuQXJyYXlTZXQucHJvdG90eXBlLmFkZCA9IGZ1bmN0aW9uIEFycmF5U2V0X2FkZChhU3RyLCBhQWxsb3dEdXBsaWNhdGVzKSB7XG4gIHZhciBzU3RyID0gaGFzTmF0aXZlTWFwID8gYVN0ciA6IHV0aWwudG9TZXRTdHJpbmcoYVN0cik7XG4gIHZhciBpc0R1cGxpY2F0ZSA9IGhhc05hdGl2ZU1hcCA/IHRoaXMuaGFzKGFTdHIpIDogaGFzLmNhbGwodGhpcy5fc2V0LCBzU3RyKTtcbiAgdmFyIGlkeCA9IHRoaXMuX2FycmF5Lmxlbmd0aDtcbiAgaWYgKCFpc0R1cGxpY2F0ZSB8fCBhQWxsb3dEdXBsaWNhdGVzKSB7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhU3RyKTtcbiAgfVxuICBpZiAoIWlzRHVwbGljYXRlKSB7XG4gICAgaWYgKGhhc05hdGl2ZU1hcCkge1xuICAgICAgdGhpcy5fc2V0LnNldChhU3RyLCBpZHgpO1xuICAgIH0gZWxzZSB7XG4gICAgICB0aGlzLl9zZXRbc1N0cl0gPSBpZHg7XG4gICAgfVxuICB9XG59O1xuXG4vKipcbiAqIElzIHRoZSBnaXZlbiBzdHJpbmcgYSBtZW1iZXIgb2YgdGhpcyBzZXQ/XG4gKlxuICogQHBhcmFtIFN0cmluZyBhU3RyXG4gKi9cbkFycmF5U2V0LnByb3RvdHlwZS5oYXMgPSBmdW5jdGlvbiBBcnJheVNldF9oYXMoYVN0cikge1xuICBpZiAoaGFzTmF0aXZlTWFwKSB7XG4gICAgcmV0dXJuIHRoaXMuX3NldC5oYXMoYVN0cik7XG4gIH0gZWxzZSB7XG4gICAgdmFyIHNTdHIgPSB1dGlsLnRvU2V0U3RyaW5nKGFTdHIpO1xuICAgIHJldHVybiBoYXMuY2FsbCh0aGlzLl9zZXQsIHNTdHIpO1xuICB9XG59O1xuXG4vKipcbiAqIFdoYXQgaXMgdGhlIGluZGV4IG9mIHRoZSBnaXZlbiBzdHJpbmcgaW4gdGhlIGFycmF5P1xuICpcbiAqIEBwYXJhbSBTdHJpbmcgYVN0clxuICovXG5BcnJheVNldC5wcm90b3R5cGUuaW5kZXhPZiA9IGZ1bmN0aW9uIEFycmF5U2V0X2luZGV4T2YoYVN0cikge1xuICBpZiAoaGFzTmF0aXZlTWFwKSB7XG4gICAgdmFyIGlkeCA9IHRoaXMuX3NldC5nZXQoYVN0cik7XG4gICAgaWYgKGlkeCA+PSAwKSB7XG4gICAgICAgIHJldHVybiBpZHg7XG4gICAgfVxuICB9IGVsc2Uge1xuICAgIHZhciBzU3RyID0gdXRpbC50b1NldFN0cmluZyhhU3RyKTtcbiAgICBpZiAoaGFzLmNhbGwodGhpcy5fc2V0LCBzU3RyKSkge1xuICAgICAgcmV0dXJuIHRoaXMuX3NldFtzU3RyXTtcbiAgICB9XG4gIH1cblxuICB0aHJvdyBuZXcgRXJyb3IoJ1wiJyArIGFTdHIgKyAnXCIgaXMgbm90IGluIHRoZSBzZXQuJyk7XG59O1xuXG4vKipcbiAqIFdoYXQgaXMgdGhlIGVsZW1lbnQgYXQgdGhlIGdpdmVuIGluZGV4P1xuICpcbiAqIEBwYXJhbSBOdW1iZXIgYUlkeFxuICovXG5BcnJheVNldC5wcm90b3R5cGUuYXQgPSBmdW5jdGlvbiBBcnJheVNldF9hdChhSWR4KSB7XG4gIGlmIChhSWR4ID49IDAgJiYgYUlkeCA8IHRoaXMuX2FycmF5Lmxlbmd0aCkge1xuICAgIHJldHVybiB0aGlzLl9hcnJheVthSWR4XTtcbiAgfVxuICB0aHJvdyBuZXcgRXJyb3IoJ05vIGVsZW1lbnQgaW5kZXhlZCBieSAnICsgYUlkeCk7XG59O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIGFycmF5IHJlcHJlc2VudGF0aW9uIG9mIHRoaXMgc2V0ICh3aGljaCBoYXMgdGhlIHByb3BlciBpbmRpY2VzXG4gKiBpbmRpY2F0ZWQgYnkgaW5kZXhPZikuIE5vdGUgdGhhdCB0aGlzIGlzIGEgY29weSBvZiB0aGUgaW50ZXJuYWwgYXJyYXkgdXNlZFxuICogZm9yIHN0b3JpbmcgdGhlIG1lbWJlcnMgc28gdGhhdCBubyBvbmUgY2FuIG1lc3Mgd2l0aCBpbnRlcm5hbCBzdGF0ZS5cbiAqL1xuQXJyYXlTZXQucHJvdG90eXBlLnRvQXJyYXkgPSBmdW5jdGlvbiBBcnJheVNldF90b0FycmF5KCkge1xuICByZXR1cm4gdGhpcy5fYXJyYXkuc2xpY2UoKTtcbn07XG5cbmV4cG9ydHMuQXJyYXlTZXQgPSBBcnJheVNldDtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL2FycmF5LXNldC5qc1xuLy8gbW9kdWxlIGlkID0gNVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTQgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbnZhciB1dGlsID0gcmVxdWlyZSgnLi91dGlsJyk7XG5cbi8qKlxuICogRGV0ZXJtaW5lIHdoZXRoZXIgbWFwcGluZ0IgaXMgYWZ0ZXIgbWFwcGluZ0Egd2l0aCByZXNwZWN0IHRvIGdlbmVyYXRlZFxuICogcG9zaXRpb24uXG4gKi9cbmZ1bmN0aW9uIGdlbmVyYXRlZFBvc2l0aW9uQWZ0ZXIobWFwcGluZ0EsIG1hcHBpbmdCKSB7XG4gIC8vIE9wdGltaXplZCBmb3IgbW9zdCBjb21tb24gY2FzZVxuICB2YXIgbGluZUEgPSBtYXBwaW5nQS5nZW5lcmF0ZWRMaW5lO1xuICB2YXIgbGluZUIgPSBtYXBwaW5nQi5nZW5lcmF0ZWRMaW5lO1xuICB2YXIgY29sdW1uQSA9IG1hcHBpbmdBLmdlbmVyYXRlZENvbHVtbjtcbiAgdmFyIGNvbHVtbkIgPSBtYXBwaW5nQi5nZW5lcmF0ZWRDb2x1bW47XG4gIHJldHVybiBsaW5lQiA+IGxpbmVBIHx8IGxpbmVCID09IGxpbmVBICYmIGNvbHVtbkIgPj0gY29sdW1uQSB8fFxuICAgICAgICAgdXRpbC5jb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZChtYXBwaW5nQSwgbWFwcGluZ0IpIDw9IDA7XG59XG5cbi8qKlxuICogQSBkYXRhIHN0cnVjdHVyZSB0byBwcm92aWRlIGEgc29ydGVkIHZpZXcgb2YgYWNjdW11bGF0ZWQgbWFwcGluZ3MgaW4gYVxuICogcGVyZm9ybWFuY2UgY29uc2Npb3VzIG1hbm5lci4gSXQgdHJhZGVzIGEgbmVnbGliYWJsZSBvdmVyaGVhZCBpbiBnZW5lcmFsXG4gKiBjYXNlIGZvciBhIGxhcmdlIHNwZWVkdXAgaW4gY2FzZSBvZiBtYXBwaW5ncyBiZWluZyBhZGRlZCBpbiBvcmRlci5cbiAqL1xuZnVuY3Rpb24gTWFwcGluZ0xpc3QoKSB7XG4gIHRoaXMuX2FycmF5ID0gW107XG4gIHRoaXMuX3NvcnRlZCA9IHRydWU7XG4gIC8vIFNlcnZlcyBhcyBpbmZpbXVtXG4gIHRoaXMuX2xhc3QgPSB7Z2VuZXJhdGVkTGluZTogLTEsIGdlbmVyYXRlZENvbHVtbjogMH07XG59XG5cbi8qKlxuICogSXRlcmF0ZSB0aHJvdWdoIGludGVybmFsIGl0ZW1zLiBUaGlzIG1ldGhvZCB0YWtlcyB0aGUgc2FtZSBhcmd1bWVudHMgdGhhdFxuICogYEFycmF5LnByb3RvdHlwZS5mb3JFYWNoYCB0YWtlcy5cbiAqXG4gKiBOT1RFOiBUaGUgb3JkZXIgb2YgdGhlIG1hcHBpbmdzIGlzIE5PVCBndWFyYW50ZWVkLlxuICovXG5NYXBwaW5nTGlzdC5wcm90b3R5cGUudW5zb3J0ZWRGb3JFYWNoID1cbiAgZnVuY3Rpb24gTWFwcGluZ0xpc3RfZm9yRWFjaChhQ2FsbGJhY2ssIGFUaGlzQXJnKSB7XG4gICAgdGhpcy5fYXJyYXkuZm9yRWFjaChhQ2FsbGJhY2ssIGFUaGlzQXJnKTtcbiAgfTtcblxuLyoqXG4gKiBBZGQgdGhlIGdpdmVuIHNvdXJjZSBtYXBwaW5nLlxuICpcbiAqIEBwYXJhbSBPYmplY3QgYU1hcHBpbmdcbiAqL1xuTWFwcGluZ0xpc3QucHJvdG90eXBlLmFkZCA9IGZ1bmN0aW9uIE1hcHBpbmdMaXN0X2FkZChhTWFwcGluZykge1xuICBpZiAoZ2VuZXJhdGVkUG9zaXRpb25BZnRlcih0aGlzLl9sYXN0LCBhTWFwcGluZykpIHtcbiAgICB0aGlzLl9sYXN0ID0gYU1hcHBpbmc7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhTWFwcGluZyk7XG4gIH0gZWxzZSB7XG4gICAgdGhpcy5fc29ydGVkID0gZmFsc2U7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhTWFwcGluZyk7XG4gIH1cbn07XG5cbi8qKlxuICogUmV0dXJucyB0aGUgZmxhdCwgc29ydGVkIGFycmF5IG9mIG1hcHBpbmdzLiBUaGUgbWFwcGluZ3MgYXJlIHNvcnRlZCBieVxuICogZ2VuZXJhdGVkIHBvc2l0aW9uLlxuICpcbiAqIFdBUk5JTkc6IFRoaXMgbWV0aG9kIHJldHVybnMgaW50ZXJuYWwgZGF0YSB3aXRob3V0IGNvcHlpbmcsIGZvclxuICogcGVyZm9ybWFuY2UuIFRoZSByZXR1cm4gdmFsdWUgbXVzdCBOT1QgYmUgbXV0YXRlZCwgYW5kIHNob3VsZCBiZSB0cmVhdGVkIGFzXG4gKiBhbiBpbW11dGFibGUgYm9ycm93LiBJZiB5b3Ugd2FudCB0byB0YWtlIG93bmVyc2hpcCwgeW91IG11c3QgbWFrZSB5b3VyIG93blxuICogY29weS5cbiAqL1xuTWFwcGluZ0xpc3QucHJvdG90eXBlLnRvQXJyYXkgPSBmdW5jdGlvbiBNYXBwaW5nTGlzdF90b0FycmF5KCkge1xuICBpZiAoIXRoaXMuX3NvcnRlZCkge1xuICAgIHRoaXMuX2FycmF5LnNvcnQodXRpbC5jb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZCk7XG4gICAgdGhpcy5fc29ydGVkID0gdHJ1ZTtcbiAgfVxuICByZXR1cm4gdGhpcy5fYXJyYXk7XG59O1xuXG5leHBvcnRzLk1hcHBpbmdMaXN0ID0gTWFwcGluZ0xpc3Q7XG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2xpYi9tYXBwaW5nLWxpc3QuanNcbi8vIG1vZHVsZSBpZCA9IDZcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgdXRpbCA9IHJlcXVpcmUoJy4vdXRpbCcpO1xudmFyIGJpbmFyeVNlYXJjaCA9IHJlcXVpcmUoJy4vYmluYXJ5LXNlYXJjaCcpO1xudmFyIEFycmF5U2V0ID0gcmVxdWlyZSgnLi9hcnJheS1zZXQnKS5BcnJheVNldDtcbnZhciBiYXNlNjRWTFEgPSByZXF1aXJlKCcuL2Jhc2U2NC12bHEnKTtcbnZhciBxdWlja1NvcnQgPSByZXF1aXJlKCcuL3F1aWNrLXNvcnQnKS5xdWlja1NvcnQ7XG5cbmZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgdmFyIHNvdXJjZU1hcCA9IGFTb3VyY2VNYXA7XG4gIGlmICh0eXBlb2YgYVNvdXJjZU1hcCA9PT0gJ3N0cmluZycpIHtcbiAgICBzb3VyY2VNYXAgPSB1dGlsLnBhcnNlU291cmNlTWFwSW5wdXQoYVNvdXJjZU1hcCk7XG4gIH1cblxuICByZXR1cm4gc291cmNlTWFwLnNlY3Rpb25zICE9IG51bGxcbiAgICA/IG5ldyBJbmRleGVkU291cmNlTWFwQ29uc3VtZXIoc291cmNlTWFwLCBhU291cmNlTWFwVVJMKVxuICAgIDogbmV3IEJhc2ljU291cmNlTWFwQ29uc3VtZXIoc291cmNlTWFwLCBhU291cmNlTWFwVVJMKTtcbn1cblxuU291cmNlTWFwQ29uc3VtZXIuZnJvbVNvdXJjZU1hcCA9IGZ1bmN0aW9uKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgcmV0dXJuIEJhc2ljU291cmNlTWFwQ29uc3VtZXIuZnJvbVNvdXJjZU1hcChhU291cmNlTWFwLCBhU291cmNlTWFwVVJMKTtcbn1cblxuLyoqXG4gKiBUaGUgdmVyc2lvbiBvZiB0aGUgc291cmNlIG1hcHBpbmcgc3BlYyB0aGF0IHdlIGFyZSBjb25zdW1pbmcuXG4gKi9cblNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8vIGBfX2dlbmVyYXRlZE1hcHBpbmdzYCBhbmQgYF9fb3JpZ2luYWxNYXBwaW5nc2AgYXJlIGFycmF5cyB0aGF0IGhvbGQgdGhlXG4vLyBwYXJzZWQgbWFwcGluZyBjb29yZGluYXRlcyBmcm9tIHRoZSBzb3VyY2UgbWFwJ3MgXCJtYXBwaW5nc1wiIGF0dHJpYnV0ZS4gVGhleVxuLy8gYXJlIGxhemlseSBpbnN0YW50aWF0ZWQsIGFjY2Vzc2VkIHZpYSB0aGUgYF9nZW5lcmF0ZWRNYXBwaW5nc2AgYW5kXG4vLyBgX29yaWdpbmFsTWFwcGluZ3NgIGdldHRlcnMgcmVzcGVjdGl2ZWx5LCBhbmQgd2Ugb25seSBwYXJzZSB0aGUgbWFwcGluZ3Ncbi8vIGFuZCBjcmVhdGUgdGhlc2UgYXJyYXlzIG9uY2UgcXVlcmllZCBmb3IgYSBzb3VyY2UgbG9jYXRpb24uIFdlIGp1bXAgdGhyb3VnaFxuLy8gdGhlc2UgaG9vcHMgYmVjYXVzZSB0aGVyZSBjYW4gYmUgbWFueSB0aG91c2FuZHMgb2YgbWFwcGluZ3MsIGFuZCBwYXJzaW5nXG4vLyB0aGVtIGlzIGV4cGVuc2l2ZSwgc28gd2Ugb25seSB3YW50IHRvIGRvIGl0IGlmIHdlIG11c3QuXG4vL1xuLy8gRWFjaCBvYmplY3QgaW4gdGhlIGFycmF5cyBpcyBvZiB0aGUgZm9ybTpcbi8vXG4vLyAgICAge1xuLy8gICAgICAgZ2VuZXJhdGVkTGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgY29kZSxcbi8vICAgICAgIGdlbmVyYXRlZENvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBjb2RlLFxuLy8gICAgICAgc291cmNlOiBUaGUgcGF0aCB0byB0aGUgb3JpZ2luYWwgc291cmNlIGZpbGUgdGhhdCBnZW5lcmF0ZWQgdGhpc1xuLy8gICAgICAgICAgICAgICBjaHVuayBvZiBjb2RlLFxuLy8gICAgICAgb3JpZ2luYWxMaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZSB0aGF0XG4vLyAgICAgICAgICAgICAgICAgICAgIGNvcnJlc3BvbmRzIHRvIHRoaXMgY2h1bmsgb2YgZ2VuZXJhdGVkIGNvZGUsXG4vLyAgICAgICBvcmlnaW5hbENvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZSB0aGF0XG4vLyAgICAgICAgICAgICAgICAgICAgICAgY29ycmVzcG9uZHMgdG8gdGhpcyBjaHVuayBvZiBnZW5lcmF0ZWQgY29kZSxcbi8vICAgICAgIG5hbWU6IFRoZSBuYW1lIG9mIHRoZSBvcmlnaW5hbCBzeW1ib2wgd2hpY2ggZ2VuZXJhdGVkIHRoaXMgY2h1bmsgb2Zcbi8vICAgICAgICAgICAgIGNvZGUuXG4vLyAgICAgfVxuLy9cbi8vIEFsbCBwcm9wZXJ0aWVzIGV4Y2VwdCBmb3IgYGdlbmVyYXRlZExpbmVgIGFuZCBgZ2VuZXJhdGVkQ29sdW1uYCBjYW4gYmVcbi8vIGBudWxsYC5cbi8vXG4vLyBgX2dlbmVyYXRlZE1hcHBpbmdzYCBpcyBvcmRlcmVkIGJ5IHRoZSBnZW5lcmF0ZWQgcG9zaXRpb25zLlxuLy9cbi8vIGBfb3JpZ2luYWxNYXBwaW5nc2AgaXMgb3JkZXJlZCBieSB0aGUgb3JpZ2luYWwgcG9zaXRpb25zLlxuXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX19nZW5lcmF0ZWRNYXBwaW5ncyA9IG51bGw7XG5PYmplY3QuZGVmaW5lUHJvcGVydHkoU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLCAnX2dlbmVyYXRlZE1hcHBpbmdzJywge1xuICBjb25maWd1cmFibGU6IHRydWUsXG4gIGVudW1lcmFibGU6IHRydWUsXG4gIGdldDogZnVuY3Rpb24gKCkge1xuICAgIGlmICghdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzKSB7XG4gICAgICB0aGlzLl9wYXJzZU1hcHBpbmdzKHRoaXMuX21hcHBpbmdzLCB0aGlzLnNvdXJjZVJvb3QpO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3M7XG4gIH1cbn0pO1xuXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX19vcmlnaW5hbE1hcHBpbmdzID0gbnVsbDtcbk9iamVjdC5kZWZpbmVQcm9wZXJ0eShTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUsICdfb3JpZ2luYWxNYXBwaW5ncycsIHtcbiAgY29uZmlndXJhYmxlOiB0cnVlLFxuICBlbnVtZXJhYmxlOiB0cnVlLFxuICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICBpZiAoIXRoaXMuX19vcmlnaW5hbE1hcHBpbmdzKSB7XG4gICAgICB0aGlzLl9wYXJzZU1hcHBpbmdzKHRoaXMuX21hcHBpbmdzLCB0aGlzLnNvdXJjZVJvb3QpO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncztcbiAgfVxufSk7XG5cblNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fY2hhcklzTWFwcGluZ1NlcGFyYXRvciA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2NoYXJJc01hcHBpbmdTZXBhcmF0b3IoYVN0ciwgaW5kZXgpIHtcbiAgICB2YXIgYyA9IGFTdHIuY2hhckF0KGluZGV4KTtcbiAgICByZXR1cm4gYyA9PT0gXCI7XCIgfHwgYyA9PT0gXCIsXCI7XG4gIH07XG5cbi8qKlxuICogUGFyc2UgdGhlIG1hcHBpbmdzIGluIGEgc3RyaW5nIGluIHRvIGEgZGF0YSBzdHJ1Y3R1cmUgd2hpY2ggd2UgY2FuIGVhc2lseVxuICogcXVlcnkgKHRoZSBvcmRlcmVkIGFycmF5cyBpbiB0aGUgYHRoaXMuX19nZW5lcmF0ZWRNYXBwaW5nc2AgYW5kXG4gKiBgdGhpcy5fX29yaWdpbmFsTWFwcGluZ3NgIHByb3BlcnRpZXMpLlxuICovXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX3BhcnNlTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKFwiU3ViY2xhc3NlcyBtdXN0IGltcGxlbWVudCBfcGFyc2VNYXBwaW5nc1wiKTtcbiAgfTtcblxuU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSID0gMTtcblNvdXJjZU1hcENvbnN1bWVyLk9SSUdJTkFMX09SREVSID0gMjtcblxuU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQgPSAxO1xuU291cmNlTWFwQ29uc3VtZXIuTEVBU1RfVVBQRVJfQk9VTkQgPSAyO1xuXG4vKipcbiAqIEl0ZXJhdGUgb3ZlciBlYWNoIG1hcHBpbmcgYmV0d2VlbiBhbiBvcmlnaW5hbCBzb3VyY2UvbGluZS9jb2x1bW4gYW5kIGFcbiAqIGdlbmVyYXRlZCBsaW5lL2NvbHVtbiBpbiB0aGlzIHNvdXJjZSBtYXAuXG4gKlxuICogQHBhcmFtIEZ1bmN0aW9uIGFDYWxsYmFja1xuICogICAgICAgIFRoZSBmdW5jdGlvbiB0aGF0IGlzIGNhbGxlZCB3aXRoIGVhY2ggbWFwcGluZy5cbiAqIEBwYXJhbSBPYmplY3QgYUNvbnRleHRcbiAqICAgICAgICBPcHRpb25hbC4gSWYgc3BlY2lmaWVkLCB0aGlzIG9iamVjdCB3aWxsIGJlIHRoZSB2YWx1ZSBvZiBgdGhpc2AgZXZlcnlcbiAqICAgICAgICB0aW1lIHRoYXQgYGFDYWxsYmFja2AgaXMgY2FsbGVkLlxuICogQHBhcmFtIGFPcmRlclxuICogICAgICAgIEVpdGhlciBgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSYCBvclxuICogICAgICAgIGBTb3VyY2VNYXBDb25zdW1lci5PUklHSU5BTF9PUkRFUmAuIFNwZWNpZmllcyB3aGV0aGVyIHlvdSB3YW50IHRvXG4gKiAgICAgICAgaXRlcmF0ZSBvdmVyIHRoZSBtYXBwaW5ncyBzb3J0ZWQgYnkgdGhlIGdlbmVyYXRlZCBmaWxlJ3MgbGluZS9jb2x1bW5cbiAqICAgICAgICBvcmRlciBvciB0aGUgb3JpZ2luYWwncyBzb3VyY2UvbGluZS9jb2x1bW4gb3JkZXIsIHJlc3BlY3RpdmVseS4gRGVmYXVsdHMgdG9cbiAqICAgICAgICBgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSYC5cbiAqL1xuU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmVhY2hNYXBwaW5nID1cbiAgZnVuY3Rpb24gU291cmNlTWFwQ29uc3VtZXJfZWFjaE1hcHBpbmcoYUNhbGxiYWNrLCBhQ29udGV4dCwgYU9yZGVyKSB7XG4gICAgdmFyIGNvbnRleHQgPSBhQ29udGV4dCB8fCBudWxsO1xuICAgIHZhciBvcmRlciA9IGFPcmRlciB8fCBTb3VyY2VNYXBDb25zdW1lci5HRU5FUkFURURfT1JERVI7XG5cbiAgICB2YXIgbWFwcGluZ3M7XG4gICAgc3dpdGNoIChvcmRlcikge1xuICAgIGNhc2UgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSOlxuICAgICAgbWFwcGluZ3MgPSB0aGlzLl9nZW5lcmF0ZWRNYXBwaW5ncztcbiAgICAgIGJyZWFrO1xuICAgIGNhc2UgU291cmNlTWFwQ29uc3VtZXIuT1JJR0lOQUxfT1JERVI6XG4gICAgICBtYXBwaW5ncyA9IHRoaXMuX29yaWdpbmFsTWFwcGluZ3M7XG4gICAgICBicmVhaztcbiAgICBkZWZhdWx0OlxuICAgICAgdGhyb3cgbmV3IEVycm9yKFwiVW5rbm93biBvcmRlciBvZiBpdGVyYXRpb24uXCIpO1xuICAgIH1cblxuICAgIHZhciBzb3VyY2VSb290ID0gdGhpcy5zb3VyY2VSb290O1xuICAgIG1hcHBpbmdzLm1hcChmdW5jdGlvbiAobWFwcGluZykge1xuICAgICAgdmFyIHNvdXJjZSA9IG1hcHBpbmcuc291cmNlID09PSBudWxsID8gbnVsbCA6IHRoaXMuX3NvdXJjZXMuYXQobWFwcGluZy5zb3VyY2UpO1xuICAgICAgc291cmNlID0gdXRpbC5jb21wdXRlU291cmNlVVJMKHNvdXJjZVJvb3QsIHNvdXJjZSwgdGhpcy5fc291cmNlTWFwVVJMKTtcbiAgICAgIHJldHVybiB7XG4gICAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgICBnZW5lcmF0ZWRMaW5lOiBtYXBwaW5nLmdlbmVyYXRlZExpbmUsXG4gICAgICAgIGdlbmVyYXRlZENvbHVtbjogbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4sXG4gICAgICAgIG9yaWdpbmFsTGluZTogbWFwcGluZy5vcmlnaW5hbExpbmUsXG4gICAgICAgIG9yaWdpbmFsQ29sdW1uOiBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uLFxuICAgICAgICBuYW1lOiBtYXBwaW5nLm5hbWUgPT09IG51bGwgPyBudWxsIDogdGhpcy5fbmFtZXMuYXQobWFwcGluZy5uYW1lKVxuICAgICAgfTtcbiAgICB9LCB0aGlzKS5mb3JFYWNoKGFDYWxsYmFjaywgY29udGV4dCk7XG4gIH07XG5cbi8qKlxuICogUmV0dXJucyBhbGwgZ2VuZXJhdGVkIGxpbmUgYW5kIGNvbHVtbiBpbmZvcm1hdGlvbiBmb3IgdGhlIG9yaWdpbmFsIHNvdXJjZSxcbiAqIGxpbmUsIGFuZCBjb2x1bW4gcHJvdmlkZWQuIElmIG5vIGNvbHVtbiBpcyBwcm92aWRlZCwgcmV0dXJucyBhbGwgbWFwcGluZ3NcbiAqIGNvcnJlc3BvbmRpbmcgdG8gYSBlaXRoZXIgdGhlIGxpbmUgd2UgYXJlIHNlYXJjaGluZyBmb3Igb3IgdGhlIG5leHRcbiAqIGNsb3Nlc3QgbGluZSB0aGF0IGhhcyBhbnkgbWFwcGluZ3MuIE90aGVyd2lzZSwgcmV0dXJucyBhbGwgbWFwcGluZ3NcbiAqIGNvcnJlc3BvbmRpbmcgdG8gdGhlIGdpdmVuIGxpbmUgYW5kIGVpdGhlciB0aGUgY29sdW1uIHdlIGFyZSBzZWFyY2hpbmcgZm9yXG4gKiBvciB0aGUgbmV4dCBjbG9zZXN0IGNvbHVtbiB0aGF0IGhhcyBhbnkgb2Zmc2V0cy5cbiAqXG4gKiBUaGUgb25seSBhcmd1bWVudCBpcyBhbiBvYmplY3Qgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIHNvdXJjZTogVGhlIGZpbGVuYW1lIG9mIHRoZSBvcmlnaW5hbCBzb3VyY2UuXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UuICBUaGUgbGluZSBudW1iZXIgaXMgMS1iYXNlZC5cbiAqICAgLSBjb2x1bW46IE9wdGlvbmFsLiB0aGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLlxuICogICAgVGhlIGNvbHVtbiBudW1iZXIgaXMgMC1iYXNlZC5cbiAqXG4gKiBhbmQgYW4gYXJyYXkgb2Ygb2JqZWN0cyBpcyByZXR1cm5lZCwgZWFjaCB3aXRoIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLCBvciBudWxsLiAgVGhlXG4gKiAgICBsaW5lIG51bWJlciBpcyAxLWJhc2VkLlxuICogICAtIGNvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBzb3VyY2UsIG9yIG51bGwuXG4gKiAgICBUaGUgY29sdW1uIG51bWJlciBpcyAwLWJhc2VkLlxuICovXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuYWxsR2VuZXJhdGVkUG9zaXRpb25zRm9yID1cbiAgZnVuY3Rpb24gU291cmNlTWFwQ29uc3VtZXJfYWxsR2VuZXJhdGVkUG9zaXRpb25zRm9yKGFBcmdzKSB7XG4gICAgdmFyIGxpbmUgPSB1dGlsLmdldEFyZyhhQXJncywgJ2xpbmUnKTtcblxuICAgIC8vIFdoZW4gdGhlcmUgaXMgbm8gZXhhY3QgbWF0Y2gsIEJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLl9maW5kTWFwcGluZ1xuICAgIC8vIHJldHVybnMgdGhlIGluZGV4IG9mIHRoZSBjbG9zZXN0IG1hcHBpbmcgbGVzcyB0aGFuIHRoZSBuZWVkbGUuIEJ5XG4gICAgLy8gc2V0dGluZyBuZWVkbGUub3JpZ2luYWxDb2x1bW4gdG8gMCwgd2UgdGh1cyBmaW5kIHRoZSBsYXN0IG1hcHBpbmcgZm9yXG4gICAgLy8gdGhlIGdpdmVuIGxpbmUsIHByb3ZpZGVkIHN1Y2ggYSBtYXBwaW5nIGV4aXN0cy5cbiAgICB2YXIgbmVlZGxlID0ge1xuICAgICAgc291cmNlOiB1dGlsLmdldEFyZyhhQXJncywgJ3NvdXJjZScpLFxuICAgICAgb3JpZ2luYWxMaW5lOiBsaW5lLFxuICAgICAgb3JpZ2luYWxDb2x1bW46IHV0aWwuZ2V0QXJnKGFBcmdzLCAnY29sdW1uJywgMClcbiAgICB9O1xuXG4gICAgbmVlZGxlLnNvdXJjZSA9IHRoaXMuX2ZpbmRTb3VyY2VJbmRleChuZWVkbGUuc291cmNlKTtcbiAgICBpZiAobmVlZGxlLnNvdXJjZSA8IDApIHtcbiAgICAgIHJldHVybiBbXTtcbiAgICB9XG5cbiAgICB2YXIgbWFwcGluZ3MgPSBbXTtcblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRNYXBwaW5nKG5lZWRsZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwib3JpZ2luYWxMaW5lXCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJvcmlnaW5hbENvbHVtblwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHV0aWwuY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYmluYXJ5U2VhcmNoLkxFQVNUX1VQUEVSX0JPVU5EKTtcbiAgICBpZiAoaW5kZXggPj0gMCkge1xuICAgICAgdmFyIG1hcHBpbmcgPSB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgaWYgKGFBcmdzLmNvbHVtbiA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIHZhciBvcmlnaW5hbExpbmUgPSBtYXBwaW5nLm9yaWdpbmFsTGluZTtcblxuICAgICAgICAvLyBJdGVyYXRlIHVudGlsIGVpdGhlciB3ZSBydW4gb3V0IG9mIG1hcHBpbmdzLCBvciB3ZSBydW4gaW50b1xuICAgICAgICAvLyBhIG1hcHBpbmcgZm9yIGEgZGlmZmVyZW50IGxpbmUgdGhhbiB0aGUgb25lIHdlIGZvdW5kLiBTaW5jZVxuICAgICAgICAvLyBtYXBwaW5ncyBhcmUgc29ydGVkLCB0aGlzIGlzIGd1YXJhbnRlZWQgdG8gZmluZCBhbGwgbWFwcGluZ3MgZm9yXG4gICAgICAgIC8vIHRoZSBsaW5lIHdlIGZvdW5kLlxuICAgICAgICB3aGlsZSAobWFwcGluZyAmJiBtYXBwaW5nLm9yaWdpbmFsTGluZSA9PT0gb3JpZ2luYWxMaW5lKSB7XG4gICAgICAgICAgbWFwcGluZ3MucHVzaCh7XG4gICAgICAgICAgICBsaW5lOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkTGluZScsIG51bGwpLFxuICAgICAgICAgICAgY29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkQ29sdW1uJywgbnVsbCksXG4gICAgICAgICAgICBsYXN0Q29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnbGFzdEdlbmVyYXRlZENvbHVtbicsIG51bGwpXG4gICAgICAgICAgfSk7XG5cbiAgICAgICAgICBtYXBwaW5nID0gdGhpcy5fb3JpZ2luYWxNYXBwaW5nc1srK2luZGV4XTtcbiAgICAgICAgfVxuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdmFyIG9yaWdpbmFsQ29sdW1uID0gbWFwcGluZy5vcmlnaW5hbENvbHVtbjtcblxuICAgICAgICAvLyBJdGVyYXRlIHVudGlsIGVpdGhlciB3ZSBydW4gb3V0IG9mIG1hcHBpbmdzLCBvciB3ZSBydW4gaW50b1xuICAgICAgICAvLyBhIG1hcHBpbmcgZm9yIGEgZGlmZmVyZW50IGxpbmUgdGhhbiB0aGUgb25lIHdlIHdlcmUgc2VhcmNoaW5nIGZvci5cbiAgICAgICAgLy8gU2luY2UgbWFwcGluZ3MgYXJlIHNvcnRlZCwgdGhpcyBpcyBndWFyYW50ZWVkIHRvIGZpbmQgYWxsIG1hcHBpbmdzIGZvclxuICAgICAgICAvLyB0aGUgbGluZSB3ZSBhcmUgc2VhcmNoaW5nIGZvci5cbiAgICAgICAgd2hpbGUgKG1hcHBpbmcgJiZcbiAgICAgICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxMaW5lID09PSBsaW5lICYmXG4gICAgICAgICAgICAgICBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uID09IG9yaWdpbmFsQ29sdW1uKSB7XG4gICAgICAgICAgbWFwcGluZ3MucHVzaCh7XG4gICAgICAgICAgICBsaW5lOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkTGluZScsIG51bGwpLFxuICAgICAgICAgICAgY29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkQ29sdW1uJywgbnVsbCksXG4gICAgICAgICAgICBsYXN0Q29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnbGFzdEdlbmVyYXRlZENvbHVtbicsIG51bGwpXG4gICAgICAgICAgfSk7XG5cbiAgICAgICAgICBtYXBwaW5nID0gdGhpcy5fb3JpZ2luYWxNYXBwaW5nc1srK2luZGV4XTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiBtYXBwaW5ncztcbiAgfTtcblxuZXhwb3J0cy5Tb3VyY2VNYXBDb25zdW1lciA9IFNvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIEEgQmFzaWNTb3VyY2VNYXBDb25zdW1lciBpbnN0YW5jZSByZXByZXNlbnRzIGEgcGFyc2VkIHNvdXJjZSBtYXAgd2hpY2ggd2UgY2FuXG4gKiBxdWVyeSBmb3IgaW5mb3JtYXRpb24gYWJvdXQgdGhlIG9yaWdpbmFsIGZpbGUgcG9zaXRpb25zIGJ5IGdpdmluZyBpdCBhIGZpbGVcbiAqIHBvc2l0aW9uIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLlxuICpcbiAqIFRoZSBmaXJzdCBwYXJhbWV0ZXIgaXMgdGhlIHJhdyBzb3VyY2UgbWFwIChlaXRoZXIgYXMgYSBKU09OIHN0cmluZywgb3JcbiAqIGFscmVhZHkgcGFyc2VkIHRvIGFuIG9iamVjdCkuIEFjY29yZGluZyB0byB0aGUgc3BlYywgc291cmNlIG1hcHMgaGF2ZSB0aGVcbiAqIGZvbGxvd2luZyBhdHRyaWJ1dGVzOlxuICpcbiAqICAgLSB2ZXJzaW9uOiBXaGljaCB2ZXJzaW9uIG9mIHRoZSBzb3VyY2UgbWFwIHNwZWMgdGhpcyBtYXAgaXMgZm9sbG93aW5nLlxuICogICAtIHNvdXJjZXM6IEFuIGFycmF5IG9mIFVSTHMgdG8gdGhlIG9yaWdpbmFsIHNvdXJjZSBmaWxlcy5cbiAqICAgLSBuYW1lczogQW4gYXJyYXkgb2YgaWRlbnRpZmllcnMgd2hpY2ggY2FuIGJlIHJlZmVycmVuY2VkIGJ5IGluZGl2aWR1YWwgbWFwcGluZ3MuXG4gKiAgIC0gc291cmNlUm9vdDogT3B0aW9uYWwuIFRoZSBVUkwgcm9vdCBmcm9tIHdoaWNoIGFsbCBzb3VyY2VzIGFyZSByZWxhdGl2ZS5cbiAqICAgLSBzb3VyY2VzQ29udGVudDogT3B0aW9uYWwuIEFuIGFycmF5IG9mIGNvbnRlbnRzIG9mIHRoZSBvcmlnaW5hbCBzb3VyY2UgZmlsZXMuXG4gKiAgIC0gbWFwcGluZ3M6IEEgc3RyaW5nIG9mIGJhc2U2NCBWTFFzIHdoaWNoIGNvbnRhaW4gdGhlIGFjdHVhbCBtYXBwaW5ncy5cbiAqICAgLSBmaWxlOiBPcHRpb25hbC4gVGhlIGdlbmVyYXRlZCBmaWxlIHRoaXMgc291cmNlIG1hcCBpcyBhc3NvY2lhdGVkIHdpdGguXG4gKlxuICogSGVyZSBpcyBhbiBleGFtcGxlIHNvdXJjZSBtYXAsIHRha2VuIGZyb20gdGhlIHNvdXJjZSBtYXAgc3BlY1swXTpcbiAqXG4gKiAgICAge1xuICogICAgICAgdmVyc2lvbiA6IDMsXG4gKiAgICAgICBmaWxlOiBcIm91dC5qc1wiLFxuICogICAgICAgc291cmNlUm9vdCA6IFwiXCIsXG4gKiAgICAgICBzb3VyY2VzOiBbXCJmb28uanNcIiwgXCJiYXIuanNcIl0sXG4gKiAgICAgICBuYW1lczogW1wic3JjXCIsIFwibWFwc1wiLCBcImFyZVwiLCBcImZ1blwiXSxcbiAqICAgICAgIG1hcHBpbmdzOiBcIkFBLEFCOztBQkNERTtcIlxuICogICAgIH1cbiAqXG4gKiBUaGUgc2Vjb25kIHBhcmFtZXRlciwgaWYgZ2l2ZW4sIGlzIGEgc3RyaW5nIHdob3NlIHZhbHVlIGlzIHRoZSBVUkxcbiAqIGF0IHdoaWNoIHRoZSBzb3VyY2UgbWFwIHdhcyBmb3VuZC4gIFRoaXMgVVJMIGlzIHVzZWQgdG8gY29tcHV0ZSB0aGVcbiAqIHNvdXJjZXMgYXJyYXkuXG4gKlxuICogWzBdOiBodHRwczovL2RvY3MuZ29vZ2xlLmNvbS9kb2N1bWVudC9kLzFVMVJHQWVoUXdSeXBVVG92RjFLUmxwaU9GemUwYi1fMmdjNmZBSDBLWTBrL2VkaXQ/cGxpPTEjXG4gKi9cbmZ1bmN0aW9uIEJhc2ljU291cmNlTWFwQ29uc3VtZXIoYVNvdXJjZU1hcCwgYVNvdXJjZU1hcFVSTCkge1xuICB2YXIgc291cmNlTWFwID0gYVNvdXJjZU1hcDtcbiAgaWYgKHR5cGVvZiBhU291cmNlTWFwID09PSAnc3RyaW5nJykge1xuICAgIHNvdXJjZU1hcCA9IHV0aWwucGFyc2VTb3VyY2VNYXBJbnB1dChhU291cmNlTWFwKTtcbiAgfVxuXG4gIHZhciB2ZXJzaW9uID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAndmVyc2lvbicpO1xuICB2YXIgc291cmNlcyA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3NvdXJjZXMnKTtcbiAgLy8gU2FzcyAzLjMgbGVhdmVzIG91dCB0aGUgJ25hbWVzJyBhcnJheSwgc28gd2UgZGV2aWF0ZSBmcm9tIHRoZSBzcGVjICh3aGljaFxuICAvLyByZXF1aXJlcyB0aGUgYXJyYXkpIHRvIHBsYXkgbmljZSBoZXJlLlxuICB2YXIgbmFtZXMgPSB1dGlsLmdldEFyZyhzb3VyY2VNYXAsICduYW1lcycsIFtdKTtcbiAgdmFyIHNvdXJjZVJvb3QgPSB1dGlsLmdldEFyZyhzb3VyY2VNYXAsICdzb3VyY2VSb290JywgbnVsbCk7XG4gIHZhciBzb3VyY2VzQ29udGVudCA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3NvdXJjZXNDb250ZW50JywgbnVsbCk7XG4gIHZhciBtYXBwaW5ncyA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ21hcHBpbmdzJyk7XG4gIHZhciBmaWxlID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAnZmlsZScsIG51bGwpO1xuXG4gIC8vIE9uY2UgYWdhaW4sIFNhc3MgZGV2aWF0ZXMgZnJvbSB0aGUgc3BlYyBhbmQgc3VwcGxpZXMgdGhlIHZlcnNpb24gYXMgYVxuICAvLyBzdHJpbmcgcmF0aGVyIHRoYW4gYSBudW1iZXIsIHNvIHdlIHVzZSBsb29zZSBlcXVhbGl0eSBjaGVja2luZyBoZXJlLlxuICBpZiAodmVyc2lvbiAhPSB0aGlzLl92ZXJzaW9uKSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCdVbnN1cHBvcnRlZCB2ZXJzaW9uOiAnICsgdmVyc2lvbik7XG4gIH1cblxuICBpZiAoc291cmNlUm9vdCkge1xuICAgIHNvdXJjZVJvb3QgPSB1dGlsLm5vcm1hbGl6ZShzb3VyY2VSb290KTtcbiAgfVxuXG4gIHNvdXJjZXMgPSBzb3VyY2VzXG4gICAgLm1hcChTdHJpbmcpXG4gICAgLy8gU29tZSBzb3VyY2UgbWFwcyBwcm9kdWNlIHJlbGF0aXZlIHNvdXJjZSBwYXRocyBsaWtlIFwiLi9mb28uanNcIiBpbnN0ZWFkIG9mXG4gICAgLy8gXCJmb28uanNcIi4gIE5vcm1hbGl6ZSB0aGVzZSBmaXJzdCBzbyB0aGF0IGZ1dHVyZSBjb21wYXJpc29ucyB3aWxsIHN1Y2NlZWQuXG4gICAgLy8gU2VlIGJ1Z3ppbC5sYS8xMDkwNzY4LlxuICAgIC5tYXAodXRpbC5ub3JtYWxpemUpXG4gICAgLy8gQWx3YXlzIGVuc3VyZSB0aGF0IGFic29sdXRlIHNvdXJjZXMgYXJlIGludGVybmFsbHkgc3RvcmVkIHJlbGF0aXZlIHRvXG4gICAgLy8gdGhlIHNvdXJjZSByb290LCBpZiB0aGUgc291cmNlIHJvb3QgaXMgYWJzb2x1dGUuIE5vdCBkb2luZyB0aGlzIHdvdWxkXG4gICAgLy8gYmUgcGFydGljdWxhcmx5IHByb2JsZW1hdGljIHdoZW4gdGhlIHNvdXJjZSByb290IGlzIGEgcHJlZml4IG9mIHRoZVxuICAgIC8vIHNvdXJjZSAodmFsaWQsIGJ1dCB3aHk/PykuIFNlZSBnaXRodWIgaXNzdWUgIzE5OSBhbmQgYnVnemlsLmxhLzExODg5ODIuXG4gICAgLm1hcChmdW5jdGlvbiAoc291cmNlKSB7XG4gICAgICByZXR1cm4gc291cmNlUm9vdCAmJiB1dGlsLmlzQWJzb2x1dGUoc291cmNlUm9vdCkgJiYgdXRpbC5pc0Fic29sdXRlKHNvdXJjZSlcbiAgICAgICAgPyB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIHNvdXJjZSlcbiAgICAgICAgOiBzb3VyY2U7XG4gICAgfSk7XG5cbiAgLy8gUGFzcyBgdHJ1ZWAgYmVsb3cgdG8gYWxsb3cgZHVwbGljYXRlIG5hbWVzIGFuZCBzb3VyY2VzLiBXaGlsZSBzb3VyY2UgbWFwc1xuICAvLyBhcmUgaW50ZW5kZWQgdG8gYmUgY29tcHJlc3NlZCBhbmQgZGVkdXBsaWNhdGVkLCB0aGUgVHlwZVNjcmlwdCBjb21waWxlclxuICAvLyBzb21ldGltZXMgZ2VuZXJhdGVzIHNvdXJjZSBtYXBzIHdpdGggZHVwbGljYXRlcyBpbiB0aGVtLiBTZWUgR2l0aHViIGlzc3VlXG4gIC8vICM3MiBhbmQgYnVnemlsLmxhLzg4OTQ5Mi5cbiAgdGhpcy5fbmFtZXMgPSBBcnJheVNldC5mcm9tQXJyYXkobmFtZXMubWFwKFN0cmluZyksIHRydWUpO1xuICB0aGlzLl9zb3VyY2VzID0gQXJyYXlTZXQuZnJvbUFycmF5KHNvdXJjZXMsIHRydWUpO1xuXG4gIHRoaXMuX2Fic29sdXRlU291cmNlcyA9IHRoaXMuX3NvdXJjZXMudG9BcnJheSgpLm1hcChmdW5jdGlvbiAocykge1xuICAgIHJldHVybiB1dGlsLmNvbXB1dGVTb3VyY2VVUkwoc291cmNlUm9vdCwgcywgYVNvdXJjZU1hcFVSTCk7XG4gIH0pO1xuXG4gIHRoaXMuc291cmNlUm9vdCA9IHNvdXJjZVJvb3Q7XG4gIHRoaXMuc291cmNlc0NvbnRlbnQgPSBzb3VyY2VzQ29udGVudDtcbiAgdGhpcy5fbWFwcGluZ3MgPSBtYXBwaW5ncztcbiAgdGhpcy5fc291cmNlTWFwVVJMID0gYVNvdXJjZU1hcFVSTDtcbiAgdGhpcy5maWxlID0gZmlsZTtcbn1cblxuQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUgPSBPYmplY3QuY3JlYXRlKFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZSk7XG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5jb25zdW1lciA9IFNvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIFV0aWxpdHkgZnVuY3Rpb24gdG8gZmluZCB0aGUgaW5kZXggb2YgYSBzb3VyY2UuICBSZXR1cm5zIC0xIGlmIG5vdFxuICogZm91bmQuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLl9maW5kU291cmNlSW5kZXggPSBmdW5jdGlvbihhU291cmNlKSB7XG4gIHZhciByZWxhdGl2ZVNvdXJjZSA9IGFTb3VyY2U7XG4gIGlmICh0aGlzLnNvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgIHJlbGF0aXZlU291cmNlID0gdXRpbC5yZWxhdGl2ZSh0aGlzLnNvdXJjZVJvb3QsIHJlbGF0aXZlU291cmNlKTtcbiAgfVxuXG4gIGlmICh0aGlzLl9zb3VyY2VzLmhhcyhyZWxhdGl2ZVNvdXJjZSkpIHtcbiAgICByZXR1cm4gdGhpcy5fc291cmNlcy5pbmRleE9mKHJlbGF0aXZlU291cmNlKTtcbiAgfVxuXG4gIC8vIE1heWJlIGFTb3VyY2UgaXMgYW4gYWJzb2x1dGUgVVJMIGFzIHJldHVybmVkIGJ5IHxzb3VyY2VzfC4gIEluXG4gIC8vIHRoaXMgY2FzZSB3ZSBjYW4ndCBzaW1wbHkgdW5kbyB0aGUgdHJhbnNmb3JtLlxuICB2YXIgaTtcbiAgZm9yIChpID0gMDsgaSA8IHRoaXMuX2Fic29sdXRlU291cmNlcy5sZW5ndGg7ICsraSkge1xuICAgIGlmICh0aGlzLl9hYnNvbHV0ZVNvdXJjZXNbaV0gPT0gYVNvdXJjZSkge1xuICAgICAgcmV0dXJuIGk7XG4gICAgfVxuICB9XG5cbiAgcmV0dXJuIC0xO1xufTtcblxuLyoqXG4gKiBDcmVhdGUgYSBCYXNpY1NvdXJjZU1hcENvbnN1bWVyIGZyb20gYSBTb3VyY2VNYXBHZW5lcmF0b3IuXG4gKlxuICogQHBhcmFtIFNvdXJjZU1hcEdlbmVyYXRvciBhU291cmNlTWFwXG4gKiAgICAgICAgVGhlIHNvdXJjZSBtYXAgdGhhdCB3aWxsIGJlIGNvbnN1bWVkLlxuICogQHBhcmFtIFN0cmluZyBhU291cmNlTWFwVVJMXG4gKiAgICAgICAgVGhlIFVSTCBhdCB3aGljaCB0aGUgc291cmNlIG1hcCBjYW4gYmUgZm91bmQgKG9wdGlvbmFsKVxuICogQHJldHVybnMgQmFzaWNTb3VyY2VNYXBDb25zdW1lclxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLmZyb21Tb3VyY2VNYXAgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9mcm9tU291cmNlTWFwKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgICB2YXIgc21jID0gT2JqZWN0LmNyZWF0ZShCYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZSk7XG5cbiAgICB2YXIgbmFtZXMgPSBzbWMuX25hbWVzID0gQXJyYXlTZXQuZnJvbUFycmF5KGFTb3VyY2VNYXAuX25hbWVzLnRvQXJyYXkoKSwgdHJ1ZSk7XG4gICAgdmFyIHNvdXJjZXMgPSBzbWMuX3NvdXJjZXMgPSBBcnJheVNldC5mcm9tQXJyYXkoYVNvdXJjZU1hcC5fc291cmNlcy50b0FycmF5KCksIHRydWUpO1xuICAgIHNtYy5zb3VyY2VSb290ID0gYVNvdXJjZU1hcC5fc291cmNlUm9vdDtcbiAgICBzbWMuc291cmNlc0NvbnRlbnQgPSBhU291cmNlTWFwLl9nZW5lcmF0ZVNvdXJjZXNDb250ZW50KHNtYy5fc291cmNlcy50b0FycmF5KCksXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBzbWMuc291cmNlUm9vdCk7XG4gICAgc21jLmZpbGUgPSBhU291cmNlTWFwLl9maWxlO1xuICAgIHNtYy5fc291cmNlTWFwVVJMID0gYVNvdXJjZU1hcFVSTDtcbiAgICBzbWMuX2Fic29sdXRlU291cmNlcyA9IHNtYy5fc291cmNlcy50b0FycmF5KCkubWFwKGZ1bmN0aW9uIChzKSB7XG4gICAgICByZXR1cm4gdXRpbC5jb21wdXRlU291cmNlVVJMKHNtYy5zb3VyY2VSb290LCBzLCBhU291cmNlTWFwVVJMKTtcbiAgICB9KTtcblxuICAgIC8vIEJlY2F1c2Ugd2UgYXJlIG1vZGlmeWluZyB0aGUgZW50cmllcyAoYnkgY29udmVydGluZyBzdHJpbmcgc291cmNlcyBhbmRcbiAgICAvLyBuYW1lcyB0byBpbmRpY2VzIGludG8gdGhlIHNvdXJjZXMgYW5kIG5hbWVzIEFycmF5U2V0cyksIHdlIGhhdmUgdG8gbWFrZVxuICAgIC8vIGEgY29weSBvZiB0aGUgZW50cnkgb3IgZWxzZSBiYWQgdGhpbmdzIGhhcHBlbi4gU2hhcmVkIG11dGFibGUgc3RhdGVcbiAgICAvLyBzdHJpa2VzIGFnYWluISBTZWUgZ2l0aHViIGlzc3VlICMxOTEuXG5cbiAgICB2YXIgZ2VuZXJhdGVkTWFwcGluZ3MgPSBhU291cmNlTWFwLl9tYXBwaW5ncy50b0FycmF5KCkuc2xpY2UoKTtcbiAgICB2YXIgZGVzdEdlbmVyYXRlZE1hcHBpbmdzID0gc21jLl9fZ2VuZXJhdGVkTWFwcGluZ3MgPSBbXTtcbiAgICB2YXIgZGVzdE9yaWdpbmFsTWFwcGluZ3MgPSBzbWMuX19vcmlnaW5hbE1hcHBpbmdzID0gW107XG5cbiAgICBmb3IgKHZhciBpID0gMCwgbGVuZ3RoID0gZ2VuZXJhdGVkTWFwcGluZ3MubGVuZ3RoOyBpIDwgbGVuZ3RoOyBpKyspIHtcbiAgICAgIHZhciBzcmNNYXBwaW5nID0gZ2VuZXJhdGVkTWFwcGluZ3NbaV07XG4gICAgICB2YXIgZGVzdE1hcHBpbmcgPSBuZXcgTWFwcGluZztcbiAgICAgIGRlc3RNYXBwaW5nLmdlbmVyYXRlZExpbmUgPSBzcmNNYXBwaW5nLmdlbmVyYXRlZExpbmU7XG4gICAgICBkZXN0TWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4gPSBzcmNNYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgaWYgKHNyY01hcHBpbmcuc291cmNlKSB7XG4gICAgICAgIGRlc3RNYXBwaW5nLnNvdXJjZSA9IHNvdXJjZXMuaW5kZXhPZihzcmNNYXBwaW5nLnNvdXJjZSk7XG4gICAgICAgIGRlc3RNYXBwaW5nLm9yaWdpbmFsTGluZSA9IHNyY01hcHBpbmcub3JpZ2luYWxMaW5lO1xuICAgICAgICBkZXN0TWFwcGluZy5vcmlnaW5hbENvbHVtbiA9IHNyY01hcHBpbmcub3JpZ2luYWxDb2x1bW47XG5cbiAgICAgICAgaWYgKHNyY01hcHBpbmcubmFtZSkge1xuICAgICAgICAgIGRlc3RNYXBwaW5nLm5hbWUgPSBuYW1lcy5pbmRleE9mKHNyY01hcHBpbmcubmFtZSk7XG4gICAgICAgIH1cblxuICAgICAgICBkZXN0T3JpZ2luYWxNYXBwaW5ncy5wdXNoKGRlc3RNYXBwaW5nKTtcbiAgICAgIH1cblxuICAgICAgZGVzdEdlbmVyYXRlZE1hcHBpbmdzLnB1c2goZGVzdE1hcHBpbmcpO1xuICAgIH1cblxuICAgIHF1aWNrU29ydChzbWMuX19vcmlnaW5hbE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zKTtcblxuICAgIHJldHVybiBzbWM7XG4gIH07XG5cbi8qKlxuICogVGhlIHZlcnNpb24gb2YgdGhlIHNvdXJjZSBtYXBwaW5nIHNwZWMgdGhhdCB3ZSBhcmUgY29uc3VtaW5nLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8qKlxuICogVGhlIGxpc3Qgb2Ygb3JpZ2luYWwgc291cmNlcy5cbiAqL1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KEJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLCAnc291cmNlcycsIHtcbiAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgcmV0dXJuIHRoaXMuX2Fic29sdXRlU291cmNlcy5zbGljZSgpO1xuICB9XG59KTtcblxuLyoqXG4gKiBQcm92aWRlIHRoZSBKSVQgd2l0aCBhIG5pY2Ugc2hhcGUgLyBoaWRkZW4gY2xhc3MuXG4gKi9cbmZ1bmN0aW9uIE1hcHBpbmcoKSB7XG4gIHRoaXMuZ2VuZXJhdGVkTGluZSA9IDA7XG4gIHRoaXMuZ2VuZXJhdGVkQ29sdW1uID0gMDtcbiAgdGhpcy5zb3VyY2UgPSBudWxsO1xuICB0aGlzLm9yaWdpbmFsTGluZSA9IG51bGw7XG4gIHRoaXMub3JpZ2luYWxDb2x1bW4gPSBudWxsO1xuICB0aGlzLm5hbWUgPSBudWxsO1xufVxuXG4vKipcbiAqIFBhcnNlIHRoZSBtYXBwaW5ncyBpbiBhIHN0cmluZyBpbiB0byBhIGRhdGEgc3RydWN0dXJlIHdoaWNoIHdlIGNhbiBlYXNpbHlcbiAqIHF1ZXJ5ICh0aGUgb3JkZXJlZCBhcnJheXMgaW4gdGhlIGB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3NgIGFuZFxuICogYHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzYCBwcm9wZXJ0aWVzKS5cbiAqL1xuQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX3BhcnNlTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdmFyIGdlbmVyYXRlZExpbmUgPSAxO1xuICAgIHZhciBwcmV2aW91c0dlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gMDtcbiAgICB2YXIgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzU291cmNlID0gMDtcbiAgICB2YXIgcHJldmlvdXNOYW1lID0gMDtcbiAgICB2YXIgbGVuZ3RoID0gYVN0ci5sZW5ndGg7XG4gICAgdmFyIGluZGV4ID0gMDtcbiAgICB2YXIgY2FjaGVkU2VnbWVudHMgPSB7fTtcbiAgICB2YXIgdGVtcCA9IHt9O1xuICAgIHZhciBvcmlnaW5hbE1hcHBpbmdzID0gW107XG4gICAgdmFyIGdlbmVyYXRlZE1hcHBpbmdzID0gW107XG4gICAgdmFyIG1hcHBpbmcsIHN0ciwgc2VnbWVudCwgZW5kLCB2YWx1ZTtcblxuICAgIHdoaWxlIChpbmRleCA8IGxlbmd0aCkge1xuICAgICAgaWYgKGFTdHIuY2hhckF0KGluZGV4KSA9PT0gJzsnKSB7XG4gICAgICAgIGdlbmVyYXRlZExpbmUrKztcbiAgICAgICAgaW5kZXgrKztcbiAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSAwO1xuICAgICAgfVxuICAgICAgZWxzZSBpZiAoYVN0ci5jaGFyQXQoaW5kZXgpID09PSAnLCcpIHtcbiAgICAgICAgaW5kZXgrKztcbiAgICAgIH1cbiAgICAgIGVsc2Uge1xuICAgICAgICBtYXBwaW5nID0gbmV3IE1hcHBpbmcoKTtcbiAgICAgICAgbWFwcGluZy5nZW5lcmF0ZWRMaW5lID0gZ2VuZXJhdGVkTGluZTtcblxuICAgICAgICAvLyBCZWNhdXNlIGVhY2ggb2Zmc2V0IGlzIGVuY29kZWQgcmVsYXRpdmUgdG8gdGhlIHByZXZpb3VzIG9uZSxcbiAgICAgICAgLy8gbWFueSBzZWdtZW50cyBvZnRlbiBoYXZlIHRoZSBzYW1lIGVuY29kaW5nLiBXZSBjYW4gZXhwbG9pdCB0aGlzXG4gICAgICAgIC8vIGZhY3QgYnkgY2FjaGluZyB0aGUgcGFyc2VkIHZhcmlhYmxlIGxlbmd0aCBmaWVsZHMgb2YgZWFjaCBzZWdtZW50LFxuICAgICAgICAvLyBhbGxvd2luZyB1cyB0byBhdm9pZCBhIHNlY29uZCBwYXJzZSBpZiB3ZSBlbmNvdW50ZXIgdGhlIHNhbWVcbiAgICAgICAgLy8gc2VnbWVudCBhZ2Fpbi5cbiAgICAgICAgZm9yIChlbmQgPSBpbmRleDsgZW5kIDwgbGVuZ3RoOyBlbmQrKykge1xuICAgICAgICAgIGlmICh0aGlzLl9jaGFySXNNYXBwaW5nU2VwYXJhdG9yKGFTdHIsIGVuZCkpIHtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBzdHIgPSBhU3RyLnNsaWNlKGluZGV4LCBlbmQpO1xuXG4gICAgICAgIHNlZ21lbnQgPSBjYWNoZWRTZWdtZW50c1tzdHJdO1xuICAgICAgICBpZiAoc2VnbWVudCkge1xuICAgICAgICAgIGluZGV4ICs9IHN0ci5sZW5ndGg7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgc2VnbWVudCA9IFtdO1xuICAgICAgICAgIHdoaWxlIChpbmRleCA8IGVuZCkge1xuICAgICAgICAgICAgYmFzZTY0VkxRLmRlY29kZShhU3RyLCBpbmRleCwgdGVtcCk7XG4gICAgICAgICAgICB2YWx1ZSA9IHRlbXAudmFsdWU7XG4gICAgICAgICAgICBpbmRleCA9IHRlbXAucmVzdDtcbiAgICAgICAgICAgIHNlZ21lbnQucHVzaCh2YWx1ZSk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAyKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlLCBidXQgbm8gbGluZSBhbmQgY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAzKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlIGFuZCBsaW5lLCBidXQgbm8gY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgY2FjaGVkU2VnbWVudHNbc3RyXSA9IHNlZ21lbnQ7XG4gICAgICAgIH1cblxuICAgICAgICAvLyBHZW5lcmF0ZWQgY29sdW1uLlxuICAgICAgICBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbiA9IHByZXZpb3VzR2VuZXJhdGVkQ29sdW1uICsgc2VnbWVudFswXTtcbiAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiAxKSB7XG4gICAgICAgICAgLy8gT3JpZ2luYWwgc291cmNlLlxuICAgICAgICAgIG1hcHBpbmcuc291cmNlID0gcHJldmlvdXNTb3VyY2UgKyBzZWdtZW50WzFdO1xuICAgICAgICAgIHByZXZpb3VzU291cmNlICs9IHNlZ21lbnRbMV07XG5cbiAgICAgICAgICAvLyBPcmlnaW5hbCBsaW5lLlxuICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxMaW5lID0gcHJldmlvdXNPcmlnaW5hbExpbmUgKyBzZWdtZW50WzJdO1xuICAgICAgICAgIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gbWFwcGluZy5vcmlnaW5hbExpbmU7XG4gICAgICAgICAgLy8gTGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkXG4gICAgICAgICAgbWFwcGluZy5vcmlnaW5hbExpbmUgKz0gMTtcblxuICAgICAgICAgIC8vIE9yaWdpbmFsIGNvbHVtbi5cbiAgICAgICAgICBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uID0gcHJldmlvdXNPcmlnaW5hbENvbHVtbiArIHNlZ21lbnRbM107XG4gICAgICAgICAgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IG1hcHBpbmcub3JpZ2luYWxDb2x1bW47XG5cbiAgICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiA0KSB7XG4gICAgICAgICAgICAvLyBPcmlnaW5hbCBuYW1lLlxuICAgICAgICAgICAgbWFwcGluZy5uYW1lID0gcHJldmlvdXNOYW1lICsgc2VnbWVudFs0XTtcbiAgICAgICAgICAgIHByZXZpb3VzTmFtZSArPSBzZWdtZW50WzRdO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuXG4gICAgICAgIGdlbmVyYXRlZE1hcHBpbmdzLnB1c2gobWFwcGluZyk7XG4gICAgICAgIGlmICh0eXBlb2YgbWFwcGluZy5vcmlnaW5hbExpbmUgPT09ICdudW1iZXInKSB7XG4gICAgICAgICAgb3JpZ2luYWxNYXBwaW5ncy5wdXNoKG1hcHBpbmcpO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfVxuXG4gICAgcXVpY2tTb3J0KGdlbmVyYXRlZE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0RlZmxhdGVkKTtcbiAgICB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3MgPSBnZW5lcmF0ZWRNYXBwaW5ncztcblxuICAgIHF1aWNrU29ydChvcmlnaW5hbE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zKTtcbiAgICB0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncyA9IG9yaWdpbmFsTWFwcGluZ3M7XG4gIH07XG5cbi8qKlxuICogRmluZCB0aGUgbWFwcGluZyB0aGF0IGJlc3QgbWF0Y2hlcyB0aGUgaHlwb3RoZXRpY2FsIFwibmVlZGxlXCIgbWFwcGluZyB0aGF0XG4gKiB3ZSBhcmUgc2VhcmNoaW5nIGZvciBpbiB0aGUgZ2l2ZW4gXCJoYXlzdGFja1wiIG9mIG1hcHBpbmdzLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fZmluZE1hcHBpbmcgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9maW5kTWFwcGluZyhhTmVlZGxlLCBhTWFwcGluZ3MsIGFMaW5lTmFtZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYUNvbHVtbk5hbWUsIGFDb21wYXJhdG9yLCBhQmlhcykge1xuICAgIC8vIFRvIHJldHVybiB0aGUgcG9zaXRpb24gd2UgYXJlIHNlYXJjaGluZyBmb3IsIHdlIG11c3QgZmlyc3QgZmluZCB0aGVcbiAgICAvLyBtYXBwaW5nIGZvciB0aGUgZ2l2ZW4gcG9zaXRpb24gYW5kIHRoZW4gcmV0dXJuIHRoZSBvcHBvc2l0ZSBwb3NpdGlvbiBpdFxuICAgIC8vIHBvaW50cyB0by4gQmVjYXVzZSB0aGUgbWFwcGluZ3MgYXJlIHNvcnRlZCwgd2UgY2FuIHVzZSBiaW5hcnkgc2VhcmNoIHRvXG4gICAgLy8gZmluZCB0aGUgYmVzdCBtYXBwaW5nLlxuXG4gICAgaWYgKGFOZWVkbGVbYUxpbmVOYW1lXSA8PSAwKSB7XG4gICAgICB0aHJvdyBuZXcgVHlwZUVycm9yKCdMaW5lIG11c3QgYmUgZ3JlYXRlciB0aGFuIG9yIGVxdWFsIHRvIDEsIGdvdCAnXG4gICAgICAgICAgICAgICAgICAgICAgICAgICsgYU5lZWRsZVthTGluZU5hbWVdKTtcbiAgICB9XG4gICAgaWYgKGFOZWVkbGVbYUNvbHVtbk5hbWVdIDwgMCkge1xuICAgICAgdGhyb3cgbmV3IFR5cGVFcnJvcignQ29sdW1uIG11c3QgYmUgZ3JlYXRlciB0aGFuIG9yIGVxdWFsIHRvIDAsIGdvdCAnXG4gICAgICAgICAgICAgICAgICAgICAgICAgICsgYU5lZWRsZVthQ29sdW1uTmFtZV0pO1xuICAgIH1cblxuICAgIHJldHVybiBiaW5hcnlTZWFyY2guc2VhcmNoKGFOZWVkbGUsIGFNYXBwaW5ncywgYUNvbXBhcmF0b3IsIGFCaWFzKTtcbiAgfTtcblxuLyoqXG4gKiBDb21wdXRlIHRoZSBsYXN0IGNvbHVtbiBmb3IgZWFjaCBnZW5lcmF0ZWQgbWFwcGluZy4gVGhlIGxhc3QgY29sdW1uIGlzXG4gKiBpbmNsdXNpdmUuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmNvbXB1dGVDb2x1bW5TcGFucyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2NvbXB1dGVDb2x1bW5TcGFucygpIHtcbiAgICBmb3IgKHZhciBpbmRleCA9IDA7IGluZGV4IDwgdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3MubGVuZ3RoOyArK2luZGV4KSB7XG4gICAgICB2YXIgbWFwcGluZyA9IHRoaXMuX2dlbmVyYXRlZE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgLy8gTWFwcGluZ3MgZG8gbm90IGNvbnRhaW4gYSBmaWVsZCBmb3IgdGhlIGxhc3QgZ2VuZXJhdGVkIGNvbHVtbnQuIFdlXG4gICAgICAvLyBjYW4gY29tZSB1cCB3aXRoIGFuIG9wdGltaXN0aWMgZXN0aW1hdGUsIGhvd2V2ZXIsIGJ5IGFzc3VtaW5nIHRoYXRcbiAgICAgIC8vIG1hcHBpbmdzIGFyZSBjb250aWd1b3VzIChpLmUuIGdpdmVuIHR3byBjb25zZWN1dGl2ZSBtYXBwaW5ncywgdGhlXG4gICAgICAvLyBmaXJzdCBtYXBwaW5nIGVuZHMgd2hlcmUgdGhlIHNlY29uZCBvbmUgc3RhcnRzKS5cbiAgICAgIGlmIChpbmRleCArIDEgPCB0aGlzLl9nZW5lcmF0ZWRNYXBwaW5ncy5sZW5ndGgpIHtcbiAgICAgICAgdmFyIG5leHRNYXBwaW5nID0gdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3NbaW5kZXggKyAxXTtcblxuICAgICAgICBpZiAobWFwcGluZy5nZW5lcmF0ZWRMaW5lID09PSBuZXh0TWFwcGluZy5nZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgICAgbWFwcGluZy5sYXN0R2VuZXJhdGVkQ29sdW1uID0gbmV4dE1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uIC0gMTtcbiAgICAgICAgICBjb250aW51ZTtcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICAvLyBUaGUgbGFzdCBtYXBwaW5nIGZvciBlYWNoIGxpbmUgc3BhbnMgdGhlIGVudGlyZSBsaW5lLlxuICAgICAgbWFwcGluZy5sYXN0R2VuZXJhdGVkQ29sdW1uID0gSW5maW5pdHk7XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIG9yaWdpbmFsIHNvdXJjZSwgbGluZSwgYW5kIGNvbHVtbiBpbmZvcm1hdGlvbiBmb3IgdGhlIGdlbmVyYXRlZFxuICogc291cmNlJ3MgbGluZSBhbmQgY29sdW1uIHBvc2l0aW9ucyBwcm92aWRlZC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgYW4gb2JqZWN0XG4gKiB3aXRoIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLiAgVGhlIGxpbmUgbnVtYmVyXG4gKiAgICAgaXMgMS1iYXNlZC5cbiAqICAgLSBjb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLiAgVGhlIGNvbHVtblxuICogICAgIG51bWJlciBpcyAwLWJhc2VkLlxuICogICAtIGJpYXM6IEVpdGhlciAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnIG9yXG4gKiAgICAgJ1NvdXJjZU1hcENvbnN1bWVyLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIHNvdXJjZTogVGhlIG9yaWdpbmFsIHNvdXJjZSBmaWxlLCBvciBudWxsLlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLCBvciBudWxsLiAgVGhlXG4gKiAgICAgbGluZSBudW1iZXIgaXMgMS1iYXNlZC5cbiAqICAgLSBjb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UsIG9yIG51bGwuICBUaGVcbiAqICAgICBjb2x1bW4gbnVtYmVyIGlzIDAtYmFzZWQuXG4gKiAgIC0gbmFtZTogVGhlIG9yaWdpbmFsIGlkZW50aWZpZXIsIG9yIG51bGwuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLm9yaWdpbmFsUG9zaXRpb25Gb3IgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9vcmlnaW5hbFBvc2l0aW9uRm9yKGFBcmdzKSB7XG4gICAgdmFyIG5lZWRsZSA9IHtcbiAgICAgIGdlbmVyYXRlZExpbmU6IHV0aWwuZ2V0QXJnKGFBcmdzLCAnbGluZScpLFxuICAgICAgZ2VuZXJhdGVkQ29sdW1uOiB1dGlsLmdldEFyZyhhQXJncywgJ2NvbHVtbicpXG4gICAgfTtcblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRNYXBwaW5nKFxuICAgICAgbmVlZGxlLFxuICAgICAgdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3MsXG4gICAgICBcImdlbmVyYXRlZExpbmVcIixcbiAgICAgIFwiZ2VuZXJhdGVkQ29sdW1uXCIsXG4gICAgICB1dGlsLmNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0RlZmxhdGVkLFxuICAgICAgdXRpbC5nZXRBcmcoYUFyZ3MsICdiaWFzJywgU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQpXG4gICAgKTtcblxuICAgIGlmIChpbmRleCA+PSAwKSB7XG4gICAgICB2YXIgbWFwcGluZyA9IHRoaXMuX2dlbmVyYXRlZE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgaWYgKG1hcHBpbmcuZ2VuZXJhdGVkTGluZSA9PT0gbmVlZGxlLmdlbmVyYXRlZExpbmUpIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdzb3VyY2UnLCBudWxsKTtcbiAgICAgICAgaWYgKHNvdXJjZSAhPT0gbnVsbCkge1xuICAgICAgICAgIHNvdXJjZSA9IHRoaXMuX3NvdXJjZXMuYXQoc291cmNlKTtcbiAgICAgICAgICBzb3VyY2UgPSB1dGlsLmNvbXB1dGVTb3VyY2VVUkwodGhpcy5zb3VyY2VSb290LCBzb3VyY2UsIHRoaXMuX3NvdXJjZU1hcFVSTCk7XG4gICAgICAgIH1cbiAgICAgICAgdmFyIG5hbWUgPSB1dGlsLmdldEFyZyhtYXBwaW5nLCAnbmFtZScsIG51bGwpO1xuICAgICAgICBpZiAobmFtZSAhPT0gbnVsbCkge1xuICAgICAgICAgIG5hbWUgPSB0aGlzLl9uYW1lcy5hdChuYW1lKTtcbiAgICAgICAgfVxuICAgICAgICByZXR1cm4ge1xuICAgICAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgICAgIGxpbmU6IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdvcmlnaW5hbExpbmUnLCBudWxsKSxcbiAgICAgICAgICBjb2x1bW46IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdvcmlnaW5hbENvbHVtbicsIG51bGwpLFxuICAgICAgICAgIG5hbWU6IG5hbWVcbiAgICAgICAgfTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICByZXR1cm4ge1xuICAgICAgc291cmNlOiBudWxsLFxuICAgICAgbGluZTogbnVsbCxcbiAgICAgIGNvbHVtbjogbnVsbCxcbiAgICAgIG5hbWU6IG51bGxcbiAgICB9O1xuICB9O1xuXG4vKipcbiAqIFJldHVybiB0cnVlIGlmIHdlIGhhdmUgdGhlIHNvdXJjZSBjb250ZW50IGZvciBldmVyeSBzb3VyY2UgaW4gdGhlIHNvdXJjZVxuICogbWFwLCBmYWxzZSBvdGhlcndpc2UuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmhhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzID1cbiAgZnVuY3Rpb24gQmFzaWNTb3VyY2VNYXBDb25zdW1lcl9oYXNDb250ZW50c09mQWxsU291cmNlcygpIHtcbiAgICBpZiAoIXRoaXMuc291cmNlc0NvbnRlbnQpIHtcbiAgICAgIHJldHVybiBmYWxzZTtcbiAgICB9XG4gICAgcmV0dXJuIHRoaXMuc291cmNlc0NvbnRlbnQubGVuZ3RoID49IHRoaXMuX3NvdXJjZXMuc2l6ZSgpICYmXG4gICAgICAhdGhpcy5zb3VyY2VzQ29udGVudC5zb21lKGZ1bmN0aW9uIChzYykgeyByZXR1cm4gc2MgPT0gbnVsbDsgfSk7XG4gIH07XG5cbi8qKlxuICogUmV0dXJucyB0aGUgb3JpZ2luYWwgc291cmNlIGNvbnRlbnQuIFRoZSBvbmx5IGFyZ3VtZW50IGlzIHRoZSB1cmwgb2YgdGhlXG4gKiBvcmlnaW5hbCBzb3VyY2UgZmlsZS4gUmV0dXJucyBudWxsIGlmIG5vIG9yaWdpbmFsIHNvdXJjZSBjb250ZW50IGlzXG4gKiBhdmFpbGFibGUuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLnNvdXJjZUNvbnRlbnRGb3IgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9zb3VyY2VDb250ZW50Rm9yKGFTb3VyY2UsIG51bGxPbk1pc3NpbmcpIHtcbiAgICBpZiAoIXRoaXMuc291cmNlc0NvbnRlbnQpIHtcbiAgICAgIHJldHVybiBudWxsO1xuICAgIH1cblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRTb3VyY2VJbmRleChhU291cmNlKTtcbiAgICBpZiAoaW5kZXggPj0gMCkge1xuICAgICAgcmV0dXJuIHRoaXMuc291cmNlc0NvbnRlbnRbaW5kZXhdO1xuICAgIH1cblxuICAgIHZhciByZWxhdGl2ZVNvdXJjZSA9IGFTb3VyY2U7XG4gICAgaWYgKHRoaXMuc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICByZWxhdGl2ZVNvdXJjZSA9IHV0aWwucmVsYXRpdmUodGhpcy5zb3VyY2VSb290LCByZWxhdGl2ZVNvdXJjZSk7XG4gICAgfVxuXG4gICAgdmFyIHVybDtcbiAgICBpZiAodGhpcy5zb3VyY2VSb290ICE9IG51bGxcbiAgICAgICAgJiYgKHVybCA9IHV0aWwudXJsUGFyc2UodGhpcy5zb3VyY2VSb290KSkpIHtcbiAgICAgIC8vIFhYWDogZmlsZTovLyBVUklzIGFuZCBhYnNvbHV0ZSBwYXRocyBsZWFkIHRvIHVuZXhwZWN0ZWQgYmVoYXZpb3IgZm9yXG4gICAgICAvLyBtYW55IHVzZXJzLiBXZSBjYW4gaGVscCB0aGVtIG91dCB3aGVuIHRoZXkgZXhwZWN0IGZpbGU6Ly8gVVJJcyB0b1xuICAgICAgLy8gYmVoYXZlIGxpa2UgaXQgd291bGQgaWYgdGhleSB3ZXJlIHJ1bm5pbmcgYSBsb2NhbCBIVFRQIHNlcnZlci4gU2VlXG4gICAgICAvLyBodHRwczovL2J1Z3ppbGxhLm1vemlsbGEub3JnL3Nob3dfYnVnLmNnaT9pZD04ODU1OTcuXG4gICAgICB2YXIgZmlsZVVyaUFic1BhdGggPSByZWxhdGl2ZVNvdXJjZS5yZXBsYWNlKC9eZmlsZTpcXC9cXC8vLCBcIlwiKTtcbiAgICAgIGlmICh1cmwuc2NoZW1lID09IFwiZmlsZVwiXG4gICAgICAgICAgJiYgdGhpcy5fc291cmNlcy5oYXMoZmlsZVVyaUFic1BhdGgpKSB7XG4gICAgICAgIHJldHVybiB0aGlzLnNvdXJjZXNDb250ZW50W3RoaXMuX3NvdXJjZXMuaW5kZXhPZihmaWxlVXJpQWJzUGF0aCldXG4gICAgICB9XG5cbiAgICAgIGlmICgoIXVybC5wYXRoIHx8IHVybC5wYXRoID09IFwiL1wiKVxuICAgICAgICAgICYmIHRoaXMuX3NvdXJjZXMuaGFzKFwiL1wiICsgcmVsYXRpdmVTb3VyY2UpKSB7XG4gICAgICAgIHJldHVybiB0aGlzLnNvdXJjZXNDb250ZW50W3RoaXMuX3NvdXJjZXMuaW5kZXhPZihcIi9cIiArIHJlbGF0aXZlU291cmNlKV07XG4gICAgICB9XG4gICAgfVxuXG4gICAgLy8gVGhpcyBmdW5jdGlvbiBpcyB1c2VkIHJlY3Vyc2l2ZWx5IGZyb21cbiAgICAvLyBJbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLnNvdXJjZUNvbnRlbnRGb3IuIEluIHRoYXQgY2FzZSwgd2VcbiAgICAvLyBkb24ndCB3YW50IHRvIHRocm93IGlmIHdlIGNhbid0IGZpbmQgdGhlIHNvdXJjZSAtIHdlIGp1c3Qgd2FudCB0b1xuICAgIC8vIHJldHVybiBudWxsLCBzbyB3ZSBwcm92aWRlIGEgZmxhZyB0byBleGl0IGdyYWNlZnVsbHkuXG4gICAgaWYgKG51bGxPbk1pc3NpbmcpIHtcbiAgICAgIHJldHVybiBudWxsO1xuICAgIH1cbiAgICBlbHNlIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignXCInICsgcmVsYXRpdmVTb3VyY2UgKyAnXCIgaXMgbm90IGluIHRoZSBTb3VyY2VNYXAuJyk7XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIGdlbmVyYXRlZCBsaW5lIGFuZCBjb2x1bW4gaW5mb3JtYXRpb24gZm9yIHRoZSBvcmlnaW5hbCBzb3VyY2UsXG4gKiBsaW5lLCBhbmQgY29sdW1uIHBvc2l0aW9ucyBwcm92aWRlZC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgYW4gb2JqZWN0IHdpdGhcbiAqIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gc291cmNlOiBUaGUgZmlsZW5hbWUgb2YgdGhlIG9yaWdpbmFsIHNvdXJjZS5cbiAqICAgLSBsaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZS4gIFRoZSBsaW5lIG51bWJlclxuICogICAgIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLiAgVGhlIGNvbHVtblxuICogICAgIG51bWJlciBpcyAwLWJhc2VkLlxuICogICAtIGJpYXM6IEVpdGhlciAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnIG9yXG4gKiAgICAgJ1NvdXJjZU1hcENvbnN1bWVyLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC4gIFRoZVxuICogICAgIGxpbmUgbnVtYmVyIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC5cbiAqICAgICBUaGUgY29sdW1uIG51bWJlciBpcyAwLWJhc2VkLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5nZW5lcmF0ZWRQb3NpdGlvbkZvciA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2dlbmVyYXRlZFBvc2l0aW9uRm9yKGFBcmdzKSB7XG4gICAgdmFyIHNvdXJjZSA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnc291cmNlJyk7XG4gICAgc291cmNlID0gdGhpcy5fZmluZFNvdXJjZUluZGV4KHNvdXJjZSk7XG4gICAgaWYgKHNvdXJjZSA8IDApIHtcbiAgICAgIHJldHVybiB7XG4gICAgICAgIGxpbmU6IG51bGwsXG4gICAgICAgIGNvbHVtbjogbnVsbCxcbiAgICAgICAgbGFzdENvbHVtbjogbnVsbFxuICAgICAgfTtcbiAgICB9XG5cbiAgICB2YXIgbmVlZGxlID0ge1xuICAgICAgc291cmNlOiBzb3VyY2UsXG4gICAgICBvcmlnaW5hbExpbmU6IHV0aWwuZ2V0QXJnKGFBcmdzLCAnbGluZScpLFxuICAgICAgb3JpZ2luYWxDb2x1bW46IHV0aWwuZ2V0QXJnKGFBcmdzLCAnY29sdW1uJylcbiAgICB9O1xuXG4gICAgdmFyIGluZGV4ID0gdGhpcy5fZmluZE1hcHBpbmcoXG4gICAgICBuZWVkbGUsXG4gICAgICB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzLFxuICAgICAgXCJvcmlnaW5hbExpbmVcIixcbiAgICAgIFwib3JpZ2luYWxDb2x1bW5cIixcbiAgICAgIHV0aWwuY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMsXG4gICAgICB1dGlsLmdldEFyZyhhQXJncywgJ2JpYXMnLCBTb3VyY2VNYXBDb25zdW1lci5HUkVBVEVTVF9MT1dFUl9CT1VORClcbiAgICApO1xuXG4gICAgaWYgKGluZGV4ID49IDApIHtcbiAgICAgIHZhciBtYXBwaW5nID0gdGhpcy5fb3JpZ2luYWxNYXBwaW5nc1tpbmRleF07XG5cbiAgICAgIGlmIChtYXBwaW5nLnNvdXJjZSA9PT0gbmVlZGxlLnNvdXJjZSkge1xuICAgICAgICByZXR1cm4ge1xuICAgICAgICAgIGxpbmU6IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdnZW5lcmF0ZWRMaW5lJywgbnVsbCksXG4gICAgICAgICAgY29sdW1uOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkQ29sdW1uJywgbnVsbCksXG4gICAgICAgICAgbGFzdENvbHVtbjogdXRpbC5nZXRBcmcobWFwcGluZywgJ2xhc3RHZW5lcmF0ZWRDb2x1bW4nLCBudWxsKVxuICAgICAgICB9O1xuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiB7XG4gICAgICBsaW5lOiBudWxsLFxuICAgICAgY29sdW1uOiBudWxsLFxuICAgICAgbGFzdENvbHVtbjogbnVsbFxuICAgIH07XG4gIH07XG5cbmV4cG9ydHMuQmFzaWNTb3VyY2VNYXBDb25zdW1lciA9IEJhc2ljU291cmNlTWFwQ29uc3VtZXI7XG5cbi8qKlxuICogQW4gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyIGluc3RhbmNlIHJlcHJlc2VudHMgYSBwYXJzZWQgc291cmNlIG1hcCB3aGljaFxuICogd2UgY2FuIHF1ZXJ5IGZvciBpbmZvcm1hdGlvbi4gSXQgZGlmZmVycyBmcm9tIEJhc2ljU291cmNlTWFwQ29uc3VtZXIgaW5cbiAqIHRoYXQgaXQgdGFrZXMgXCJpbmRleGVkXCIgc291cmNlIG1hcHMgKGkuZS4gb25lcyB3aXRoIGEgXCJzZWN0aW9uc1wiIGZpZWxkKSBhc1xuICogaW5wdXQuXG4gKlxuICogVGhlIGZpcnN0IHBhcmFtZXRlciBpcyBhIHJhdyBzb3VyY2UgbWFwIChlaXRoZXIgYXMgYSBKU09OIHN0cmluZywgb3IgYWxyZWFkeVxuICogcGFyc2VkIHRvIGFuIG9iamVjdCkuIEFjY29yZGluZyB0byB0aGUgc3BlYyBmb3IgaW5kZXhlZCBzb3VyY2UgbWFwcywgdGhleVxuICogaGF2ZSB0aGUgZm9sbG93aW5nIGF0dHJpYnV0ZXM6XG4gKlxuICogICAtIHZlcnNpb246IFdoaWNoIHZlcnNpb24gb2YgdGhlIHNvdXJjZSBtYXAgc3BlYyB0aGlzIG1hcCBpcyBmb2xsb3dpbmcuXG4gKiAgIC0gZmlsZTogT3B0aW9uYWwuIFRoZSBnZW5lcmF0ZWQgZmlsZSB0aGlzIHNvdXJjZSBtYXAgaXMgYXNzb2NpYXRlZCB3aXRoLlxuICogICAtIHNlY3Rpb25zOiBBIGxpc3Qgb2Ygc2VjdGlvbiBkZWZpbml0aW9ucy5cbiAqXG4gKiBFYWNoIHZhbHVlIHVuZGVyIHRoZSBcInNlY3Rpb25zXCIgZmllbGQgaGFzIHR3byBmaWVsZHM6XG4gKiAgIC0gb2Zmc2V0OiBUaGUgb2Zmc2V0IGludG8gdGhlIG9yaWdpbmFsIHNwZWNpZmllZCBhdCB3aGljaCB0aGlzIHNlY3Rpb25cbiAqICAgICAgIGJlZ2lucyB0byBhcHBseSwgZGVmaW5lZCBhcyBhbiBvYmplY3Qgd2l0aCBhIFwibGluZVwiIGFuZCBcImNvbHVtblwiXG4gKiAgICAgICBmaWVsZC5cbiAqICAgLSBtYXA6IEEgc291cmNlIG1hcCBkZWZpbml0aW9uLiBUaGlzIHNvdXJjZSBtYXAgY291bGQgYWxzbyBiZSBpbmRleGVkLFxuICogICAgICAgYnV0IGRvZXNuJ3QgaGF2ZSB0byBiZS5cbiAqXG4gKiBJbnN0ZWFkIG9mIHRoZSBcIm1hcFwiIGZpZWxkLCBpdCdzIGFsc28gcG9zc2libGUgdG8gaGF2ZSBhIFwidXJsXCIgZmllbGRcbiAqIHNwZWNpZnlpbmcgYSBVUkwgdG8gcmV0cmlldmUgYSBzb3VyY2UgbWFwIGZyb20sIGJ1dCB0aGF0J3MgY3VycmVudGx5XG4gKiB1bnN1cHBvcnRlZC5cbiAqXG4gKiBIZXJlJ3MgYW4gZXhhbXBsZSBzb3VyY2UgbWFwLCB0YWtlbiBmcm9tIHRoZSBzb3VyY2UgbWFwIHNwZWNbMF0sIGJ1dFxuICogbW9kaWZpZWQgdG8gb21pdCBhIHNlY3Rpb24gd2hpY2ggdXNlcyB0aGUgXCJ1cmxcIiBmaWVsZC5cbiAqXG4gKiAge1xuICogICAgdmVyc2lvbiA6IDMsXG4gKiAgICBmaWxlOiBcImFwcC5qc1wiLFxuICogICAgc2VjdGlvbnM6IFt7XG4gKiAgICAgIG9mZnNldDoge2xpbmU6MTAwLCBjb2x1bW46MTB9LFxuICogICAgICBtYXA6IHtcbiAqICAgICAgICB2ZXJzaW9uIDogMyxcbiAqICAgICAgICBmaWxlOiBcInNlY3Rpb24uanNcIixcbiAqICAgICAgICBzb3VyY2VzOiBbXCJmb28uanNcIiwgXCJiYXIuanNcIl0sXG4gKiAgICAgICAgbmFtZXM6IFtcInNyY1wiLCBcIm1hcHNcIiwgXCJhcmVcIiwgXCJmdW5cIl0sXG4gKiAgICAgICAgbWFwcGluZ3M6IFwiQUFBQSxFOztBQkNERTtcIlxuICogICAgICB9XG4gKiAgICB9XSxcbiAqICB9XG4gKlxuICogVGhlIHNlY29uZCBwYXJhbWV0ZXIsIGlmIGdpdmVuLCBpcyBhIHN0cmluZyB3aG9zZSB2YWx1ZSBpcyB0aGUgVVJMXG4gKiBhdCB3aGljaCB0aGUgc291cmNlIG1hcCB3YXMgZm91bmQuICBUaGlzIFVSTCBpcyB1c2VkIHRvIGNvbXB1dGUgdGhlXG4gKiBzb3VyY2VzIGFycmF5LlxuICpcbiAqIFswXTogaHR0cHM6Ly9kb2NzLmdvb2dsZS5jb20vZG9jdW1lbnQvZC8xVTFSR0FlaFF3UnlwVVRvdkYxS1JscGlPRnplMGItXzJnYzZmQUgwS1kway9lZGl0I2hlYWRpbmc9aC41MzVlczN4ZXByZ3RcbiAqL1xuZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyKGFTb3VyY2VNYXAsIGFTb3VyY2VNYXBVUkwpIHtcbiAgdmFyIHNvdXJjZU1hcCA9IGFTb3VyY2VNYXA7XG4gIGlmICh0eXBlb2YgYVNvdXJjZU1hcCA9PT0gJ3N0cmluZycpIHtcbiAgICBzb3VyY2VNYXAgPSB1dGlsLnBhcnNlU291cmNlTWFwSW5wdXQoYVNvdXJjZU1hcCk7XG4gIH1cblxuICB2YXIgdmVyc2lvbiA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3ZlcnNpb24nKTtcbiAgdmFyIHNlY3Rpb25zID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAnc2VjdGlvbnMnKTtcblxuICBpZiAodmVyc2lvbiAhPSB0aGlzLl92ZXJzaW9uKSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCdVbnN1cHBvcnRlZCB2ZXJzaW9uOiAnICsgdmVyc2lvbik7XG4gIH1cblxuICB0aGlzLl9zb3VyY2VzID0gbmV3IEFycmF5U2V0KCk7XG4gIHRoaXMuX25hbWVzID0gbmV3IEFycmF5U2V0KCk7XG5cbiAgdmFyIGxhc3RPZmZzZXQgPSB7XG4gICAgbGluZTogLTEsXG4gICAgY29sdW1uOiAwXG4gIH07XG4gIHRoaXMuX3NlY3Rpb25zID0gc2VjdGlvbnMubWFwKGZ1bmN0aW9uIChzKSB7XG4gICAgaWYgKHMudXJsKSB7XG4gICAgICAvLyBUaGUgdXJsIGZpZWxkIHdpbGwgcmVxdWlyZSBzdXBwb3J0IGZvciBhc3luY2hyb25pY2l0eS5cbiAgICAgIC8vIFNlZSBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL2lzc3Vlcy8xNlxuICAgICAgdGhyb3cgbmV3IEVycm9yKCdTdXBwb3J0IGZvciB1cmwgZmllbGQgaW4gc2VjdGlvbnMgbm90IGltcGxlbWVudGVkLicpO1xuICAgIH1cbiAgICB2YXIgb2Zmc2V0ID0gdXRpbC5nZXRBcmcocywgJ29mZnNldCcpO1xuICAgIHZhciBvZmZzZXRMaW5lID0gdXRpbC5nZXRBcmcob2Zmc2V0LCAnbGluZScpO1xuICAgIHZhciBvZmZzZXRDb2x1bW4gPSB1dGlsLmdldEFyZyhvZmZzZXQsICdjb2x1bW4nKTtcblxuICAgIGlmIChvZmZzZXRMaW5lIDwgbGFzdE9mZnNldC5saW5lIHx8XG4gICAgICAgIChvZmZzZXRMaW5lID09PSBsYXN0T2Zmc2V0LmxpbmUgJiYgb2Zmc2V0Q29sdW1uIDwgbGFzdE9mZnNldC5jb2x1bW4pKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ1NlY3Rpb24gb2Zmc2V0cyBtdXN0IGJlIG9yZGVyZWQgYW5kIG5vbi1vdmVybGFwcGluZy4nKTtcbiAgICB9XG4gICAgbGFzdE9mZnNldCA9IG9mZnNldDtcblxuICAgIHJldHVybiB7XG4gICAgICBnZW5lcmF0ZWRPZmZzZXQ6IHtcbiAgICAgICAgLy8gVGhlIG9mZnNldCBmaWVsZHMgYXJlIDAtYmFzZWQsIGJ1dCB3ZSB1c2UgMS1iYXNlZCBpbmRpY2VzIHdoZW5cbiAgICAgICAgLy8gZW5jb2RpbmcvZGVjb2RpbmcgZnJvbSBWTFEuXG4gICAgICAgIGdlbmVyYXRlZExpbmU6IG9mZnNldExpbmUgKyAxLFxuICAgICAgICBnZW5lcmF0ZWRDb2x1bW46IG9mZnNldENvbHVtbiArIDFcbiAgICAgIH0sXG4gICAgICBjb25zdW1lcjogbmV3IFNvdXJjZU1hcENvbnN1bWVyKHV0aWwuZ2V0QXJnKHMsICdtYXAnKSwgYVNvdXJjZU1hcFVSTClcbiAgICB9XG4gIH0pO1xufVxuXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlID0gT2JqZWN0LmNyZWF0ZShTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUpO1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5jb25zdHJ1Y3RvciA9IFNvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIFRoZSB2ZXJzaW9uIG9mIHRoZSBzb3VyY2UgbWFwcGluZyBzcGVjIHRoYXQgd2UgYXJlIGNvbnN1bWluZy5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8qKlxuICogVGhlIGxpc3Qgb2Ygb3JpZ2luYWwgc291cmNlcy5cbiAqL1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUsICdzb3VyY2VzJywge1xuICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICB2YXIgc291cmNlcyA9IFtdO1xuICAgIGZvciAodmFyIGkgPSAwOyBpIDwgdGhpcy5fc2VjdGlvbnMubGVuZ3RoOyBpKyspIHtcbiAgICAgIGZvciAodmFyIGogPSAwOyBqIDwgdGhpcy5fc2VjdGlvbnNbaV0uY29uc3VtZXIuc291cmNlcy5sZW5ndGg7IGorKykge1xuICAgICAgICBzb3VyY2VzLnB1c2godGhpcy5fc2VjdGlvbnNbaV0uY29uc3VtZXIuc291cmNlc1tqXSk7XG4gICAgICB9XG4gICAgfVxuICAgIHJldHVybiBzb3VyY2VzO1xuICB9XG59KTtcblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBvcmlnaW5hbCBzb3VyY2UsIGxpbmUsIGFuZCBjb2x1bW4gaW5mb3JtYXRpb24gZm9yIHRoZSBnZW5lcmF0ZWRcbiAqIHNvdXJjZSdzIGxpbmUgYW5kIGNvbHVtbiBwb3NpdGlvbnMgcHJvdmlkZWQuIFRoZSBvbmx5IGFyZ3VtZW50IGlzIGFuIG9iamVjdFxuICogd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZS4gIFRoZSBsaW5lIG51bWJlclxuICogICAgIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZS4gIFRoZSBjb2x1bW5cbiAqICAgICBudW1iZXIgaXMgMC1iYXNlZC5cbiAqXG4gKiBhbmQgYW4gb2JqZWN0IGlzIHJldHVybmVkIHdpdGggdGhlIGZvbGxvd2luZyBwcm9wZXJ0aWVzOlxuICpcbiAqICAgLSBzb3VyY2U6IFRoZSBvcmlnaW5hbCBzb3VyY2UgZmlsZSwgb3IgbnVsbC5cbiAqICAgLSBsaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZSwgb3IgbnVsbC4gIFRoZVxuICogICAgIGxpbmUgbnVtYmVyIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLCBvciBudWxsLiAgVGhlXG4gKiAgICAgY29sdW1uIG51bWJlciBpcyAwLWJhc2VkLlxuICogICAtIG5hbWU6IFRoZSBvcmlnaW5hbCBpZGVudGlmaWVyLCBvciBudWxsLlxuICovXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLm9yaWdpbmFsUG9zaXRpb25Gb3IgPVxuICBmdW5jdGlvbiBJbmRleGVkU291cmNlTWFwQ29uc3VtZXJfb3JpZ2luYWxQb3NpdGlvbkZvcihhQXJncykge1xuICAgIHZhciBuZWVkbGUgPSB7XG4gICAgICBnZW5lcmF0ZWRMaW5lOiB1dGlsLmdldEFyZyhhQXJncywgJ2xpbmUnKSxcbiAgICAgIGdlbmVyYXRlZENvbHVtbjogdXRpbC5nZXRBcmcoYUFyZ3MsICdjb2x1bW4nKVxuICAgIH07XG5cbiAgICAvLyBGaW5kIHRoZSBzZWN0aW9uIGNvbnRhaW5pbmcgdGhlIGdlbmVyYXRlZCBwb3NpdGlvbiB3ZSdyZSB0cnlpbmcgdG8gbWFwXG4gICAgLy8gdG8gYW4gb3JpZ2luYWwgcG9zaXRpb24uXG4gICAgdmFyIHNlY3Rpb25JbmRleCA9IGJpbmFyeVNlYXJjaC5zZWFyY2gobmVlZGxlLCB0aGlzLl9zZWN0aW9ucyxcbiAgICAgIGZ1bmN0aW9uKG5lZWRsZSwgc2VjdGlvbikge1xuICAgICAgICB2YXIgY21wID0gbmVlZGxlLmdlbmVyYXRlZExpbmUgLSBzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lO1xuICAgICAgICBpZiAoY21wKSB7XG4gICAgICAgICAgcmV0dXJuIGNtcDtcbiAgICAgICAgfVxuXG4gICAgICAgIHJldHVybiAobmVlZGxlLmdlbmVyYXRlZENvbHVtbiAtXG4gICAgICAgICAgICAgICAgc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkQ29sdW1uKTtcbiAgICAgIH0pO1xuICAgIHZhciBzZWN0aW9uID0gdGhpcy5fc2VjdGlvbnNbc2VjdGlvbkluZGV4XTtcblxuICAgIGlmICghc2VjdGlvbikge1xuICAgICAgcmV0dXJuIHtcbiAgICAgICAgc291cmNlOiBudWxsLFxuICAgICAgICBsaW5lOiBudWxsLFxuICAgICAgICBjb2x1bW46IG51bGwsXG4gICAgICAgIG5hbWU6IG51bGxcbiAgICAgIH07XG4gICAgfVxuXG4gICAgcmV0dXJuIHNlY3Rpb24uY29uc3VtZXIub3JpZ2luYWxQb3NpdGlvbkZvcih7XG4gICAgICBsaW5lOiBuZWVkbGUuZ2VuZXJhdGVkTGluZSAtXG4gICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lIC0gMSksXG4gICAgICBjb2x1bW46IG5lZWRsZS5nZW5lcmF0ZWRDb2x1bW4gLVxuICAgICAgICAoc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkTGluZSA9PT0gbmVlZGxlLmdlbmVyYXRlZExpbmVcbiAgICAgICAgID8gc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkQ29sdW1uIC0gMVxuICAgICAgICAgOiAwKSxcbiAgICAgIGJpYXM6IGFBcmdzLmJpYXNcbiAgICB9KTtcbiAgfTtcblxuLyoqXG4gKiBSZXR1cm4gdHJ1ZSBpZiB3ZSBoYXZlIHRoZSBzb3VyY2UgY29udGVudCBmb3IgZXZlcnkgc291cmNlIGluIHRoZSBzb3VyY2VcbiAqIG1hcCwgZmFsc2Ugb3RoZXJ3aXNlLlxuICovXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmhhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzID1cbiAgZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyX2hhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzKCkge1xuICAgIHJldHVybiB0aGlzLl9zZWN0aW9ucy5ldmVyeShmdW5jdGlvbiAocykge1xuICAgICAgcmV0dXJuIHMuY29uc3VtZXIuaGFzQ29udGVudHNPZkFsbFNvdXJjZXMoKTtcbiAgICB9KTtcbiAgfTtcblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBvcmlnaW5hbCBzb3VyY2UgY29udGVudC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgdGhlIHVybCBvZiB0aGVcbiAqIG9yaWdpbmFsIHNvdXJjZSBmaWxlLiBSZXR1cm5zIG51bGwgaWYgbm8gb3JpZ2luYWwgc291cmNlIGNvbnRlbnQgaXNcbiAqIGF2YWlsYWJsZS5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5zb3VyY2VDb250ZW50Rm9yID1cbiAgZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyX3NvdXJjZUNvbnRlbnRGb3IoYVNvdXJjZSwgbnVsbE9uTWlzc2luZykge1xuICAgIGZvciAodmFyIGkgPSAwOyBpIDwgdGhpcy5fc2VjdGlvbnMubGVuZ3RoOyBpKyspIHtcbiAgICAgIHZhciBzZWN0aW9uID0gdGhpcy5fc2VjdGlvbnNbaV07XG5cbiAgICAgIHZhciBjb250ZW50ID0gc2VjdGlvbi5jb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKGFTb3VyY2UsIHRydWUpO1xuICAgICAgaWYgKGNvbnRlbnQpIHtcbiAgICAgICAgcmV0dXJuIGNvbnRlbnQ7XG4gICAgICB9XG4gICAgfVxuICAgIGlmIChudWxsT25NaXNzaW5nKSB7XG4gICAgICByZXR1cm4gbnVsbDtcbiAgICB9XG4gICAgZWxzZSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ1wiJyArIGFTb3VyY2UgKyAnXCIgaXMgbm90IGluIHRoZSBTb3VyY2VNYXAuJyk7XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIGdlbmVyYXRlZCBsaW5lIGFuZCBjb2x1bW4gaW5mb3JtYXRpb24gZm9yIHRoZSBvcmlnaW5hbCBzb3VyY2UsXG4gKiBsaW5lLCBhbmQgY29sdW1uIHBvc2l0aW9ucyBwcm92aWRlZC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgYW4gb2JqZWN0IHdpdGhcbiAqIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gc291cmNlOiBUaGUgZmlsZW5hbWUgb2YgdGhlIG9yaWdpbmFsIHNvdXJjZS5cbiAqICAgLSBsaW5lOiBUaGUgbGluZSBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZS4gIFRoZSBsaW5lIG51bWJlclxuICogICAgIGlzIDEtYmFzZWQuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLiAgVGhlIGNvbHVtblxuICogICAgIG51bWJlciBpcyAwLWJhc2VkLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC4gIFRoZVxuICogICAgIGxpbmUgbnVtYmVyIGlzIDEtYmFzZWQuIFxuICogICAtIGNvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBzb3VyY2UsIG9yIG51bGwuXG4gKiAgICAgVGhlIGNvbHVtbiBudW1iZXIgaXMgMC1iYXNlZC5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5nZW5lcmF0ZWRQb3NpdGlvbkZvciA9XG4gIGZ1bmN0aW9uIEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lcl9nZW5lcmF0ZWRQb3NpdGlvbkZvcihhQXJncykge1xuICAgIGZvciAodmFyIGkgPSAwOyBpIDwgdGhpcy5fc2VjdGlvbnMubGVuZ3RoOyBpKyspIHtcbiAgICAgIHZhciBzZWN0aW9uID0gdGhpcy5fc2VjdGlvbnNbaV07XG5cbiAgICAgIC8vIE9ubHkgY29uc2lkZXIgdGhpcyBzZWN0aW9uIGlmIHRoZSByZXF1ZXN0ZWQgc291cmNlIGlzIGluIHRoZSBsaXN0IG9mXG4gICAgICAvLyBzb3VyY2VzIG9mIHRoZSBjb25zdW1lci5cbiAgICAgIGlmIChzZWN0aW9uLmNvbnN1bWVyLl9maW5kU291cmNlSW5kZXgodXRpbC5nZXRBcmcoYUFyZ3MsICdzb3VyY2UnKSkgPT09IC0xKSB7XG4gICAgICAgIGNvbnRpbnVlO1xuICAgICAgfVxuICAgICAgdmFyIGdlbmVyYXRlZFBvc2l0aW9uID0gc2VjdGlvbi5jb25zdW1lci5nZW5lcmF0ZWRQb3NpdGlvbkZvcihhQXJncyk7XG4gICAgICBpZiAoZ2VuZXJhdGVkUG9zaXRpb24pIHtcbiAgICAgICAgdmFyIHJldCA9IHtcbiAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWRQb3NpdGlvbi5saW5lICtcbiAgICAgICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lIC0gMSksXG4gICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWRQb3NpdGlvbi5jb2x1bW4gK1xuICAgICAgICAgICAgKHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZExpbmUgPT09IGdlbmVyYXRlZFBvc2l0aW9uLmxpbmVcbiAgICAgICAgICAgICA/IHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZENvbHVtbiAtIDFcbiAgICAgICAgICAgICA6IDApXG4gICAgICAgIH07XG4gICAgICAgIHJldHVybiByZXQ7XG4gICAgICB9XG4gICAgfVxuXG4gICAgcmV0dXJuIHtcbiAgICAgIGxpbmU6IG51bGwsXG4gICAgICBjb2x1bW46IG51bGxcbiAgICB9O1xuICB9O1xuXG4vKipcbiAqIFBhcnNlIHRoZSBtYXBwaW5ncyBpbiBhIHN0cmluZyBpbiB0byBhIGRhdGEgc3RydWN0dXJlIHdoaWNoIHdlIGNhbiBlYXNpbHlcbiAqIHF1ZXJ5ICh0aGUgb3JkZXJlZCBhcnJheXMgaW4gdGhlIGB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3NgIGFuZFxuICogYHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzYCBwcm9wZXJ0aWVzKS5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fcGFyc2VNYXBwaW5ncyA9XG4gIGZ1bmN0aW9uIEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzID0gW107XG4gICAgdGhpcy5fX29yaWdpbmFsTWFwcGluZ3MgPSBbXTtcbiAgICBmb3IgKHZhciBpID0gMDsgaSA8IHRoaXMuX3NlY3Rpb25zLmxlbmd0aDsgaSsrKSB7XG4gICAgICB2YXIgc2VjdGlvbiA9IHRoaXMuX3NlY3Rpb25zW2ldO1xuICAgICAgdmFyIHNlY3Rpb25NYXBwaW5ncyA9IHNlY3Rpb24uY29uc3VtZXIuX2dlbmVyYXRlZE1hcHBpbmdzO1xuICAgICAgZm9yICh2YXIgaiA9IDA7IGogPCBzZWN0aW9uTWFwcGluZ3MubGVuZ3RoOyBqKyspIHtcbiAgICAgICAgdmFyIG1hcHBpbmcgPSBzZWN0aW9uTWFwcGluZ3Nbal07XG5cbiAgICAgICAgdmFyIHNvdXJjZSA9IHNlY3Rpb24uY29uc3VtZXIuX3NvdXJjZXMuYXQobWFwcGluZy5zb3VyY2UpO1xuICAgICAgICBzb3VyY2UgPSB1dGlsLmNvbXB1dGVTb3VyY2VVUkwoc2VjdGlvbi5jb25zdW1lci5zb3VyY2VSb290LCBzb3VyY2UsIHRoaXMuX3NvdXJjZU1hcFVSTCk7XG4gICAgICAgIHRoaXMuX3NvdXJjZXMuYWRkKHNvdXJjZSk7XG4gICAgICAgIHNvdXJjZSA9IHRoaXMuX3NvdXJjZXMuaW5kZXhPZihzb3VyY2UpO1xuXG4gICAgICAgIHZhciBuYW1lID0gbnVsbDtcbiAgICAgICAgaWYgKG1hcHBpbmcubmFtZSkge1xuICAgICAgICAgIG5hbWUgPSBzZWN0aW9uLmNvbnN1bWVyLl9uYW1lcy5hdChtYXBwaW5nLm5hbWUpO1xuICAgICAgICAgIHRoaXMuX25hbWVzLmFkZChuYW1lKTtcbiAgICAgICAgICBuYW1lID0gdGhpcy5fbmFtZXMuaW5kZXhPZihuYW1lKTtcbiAgICAgICAgfVxuXG4gICAgICAgIC8vIFRoZSBtYXBwaW5ncyBjb21pbmcgZnJvbSB0aGUgY29uc3VtZXIgZm9yIHRoZSBzZWN0aW9uIGhhdmVcbiAgICAgICAgLy8gZ2VuZXJhdGVkIHBvc2l0aW9ucyByZWxhdGl2ZSB0byB0aGUgc3RhcnQgb2YgdGhlIHNlY3Rpb24sIHNvIHdlXG4gICAgICAgIC8vIG5lZWQgdG8gb2Zmc2V0IHRoZW0gdG8gYmUgcmVsYXRpdmUgdG8gdGhlIHN0YXJ0IG9mIHRoZSBjb25jYXRlbmF0ZWRcbiAgICAgICAgLy8gZ2VuZXJhdGVkIGZpbGUuXG4gICAgICAgIHZhciBhZGp1c3RlZE1hcHBpbmcgPSB7XG4gICAgICAgICAgc291cmNlOiBzb3VyY2UsXG4gICAgICAgICAgZ2VuZXJhdGVkTGluZTogbWFwcGluZy5nZW5lcmF0ZWRMaW5lICtcbiAgICAgICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lIC0gMSksXG4gICAgICAgICAgZ2VuZXJhdGVkQ29sdW1uOiBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbiArXG4gICAgICAgICAgICAoc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkTGluZSA9PT0gbWFwcGluZy5nZW5lcmF0ZWRMaW5lXG4gICAgICAgICAgICA/IHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZENvbHVtbiAtIDFcbiAgICAgICAgICAgIDogMCksXG4gICAgICAgICAgb3JpZ2luYWxMaW5lOiBtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICBvcmlnaW5hbENvbHVtbjogbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICBuYW1lOiBuYW1lXG4gICAgICAgIH07XG5cbiAgICAgICAgdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzLnB1c2goYWRqdXN0ZWRNYXBwaW5nKTtcbiAgICAgICAgaWYgKHR5cGVvZiBhZGp1c3RlZE1hcHBpbmcub3JpZ2luYWxMaW5lID09PSAnbnVtYmVyJykge1xuICAgICAgICAgIHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzLnB1c2goYWRqdXN0ZWRNYXBwaW5nKTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cblxuICAgIHF1aWNrU29ydCh0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3MsIHV0aWwuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zRGVmbGF0ZWQpO1xuICAgIHF1aWNrU29ydCh0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncywgdXRpbC5jb21wYXJlQnlPcmlnaW5hbFBvc2l0aW9ucyk7XG4gIH07XG5cbmV4cG9ydHMuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyID0gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qc1xuLy8gbW9kdWxlIGlkID0gN1xuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbmV4cG9ydHMuR1JFQVRFU1RfTE9XRVJfQk9VTkQgPSAxO1xuZXhwb3J0cy5MRUFTVF9VUFBFUl9CT1VORCA9IDI7XG5cbi8qKlxuICogUmVjdXJzaXZlIGltcGxlbWVudGF0aW9uIG9mIGJpbmFyeSBzZWFyY2guXG4gKlxuICogQHBhcmFtIGFMb3cgSW5kaWNlcyBoZXJlIGFuZCBsb3dlciBkbyBub3QgY29udGFpbiB0aGUgbmVlZGxlLlxuICogQHBhcmFtIGFIaWdoIEluZGljZXMgaGVyZSBhbmQgaGlnaGVyIGRvIG5vdCBjb250YWluIHRoZSBuZWVkbGUuXG4gKiBAcGFyYW0gYU5lZWRsZSBUaGUgZWxlbWVudCBiZWluZyBzZWFyY2hlZCBmb3IuXG4gKiBAcGFyYW0gYUhheXN0YWNrIFRoZSBub24tZW1wdHkgYXJyYXkgYmVpbmcgc2VhcmNoZWQuXG4gKiBAcGFyYW0gYUNvbXBhcmUgRnVuY3Rpb24gd2hpY2ggdGFrZXMgdHdvIGVsZW1lbnRzIGFuZCByZXR1cm5zIC0xLCAwLCBvciAxLlxuICogQHBhcmFtIGFCaWFzIEVpdGhlciAnYmluYXJ5U2VhcmNoLkdSRUFURVNUX0xPV0VSX0JPVU5EJyBvclxuICogICAgICdiaW5hcnlTZWFyY2guTEVBU1RfVVBQRVJfQk9VTkQnLiBTcGVjaWZpZXMgd2hldGhlciB0byByZXR1cm4gdGhlXG4gKiAgICAgY2xvc2VzdCBlbGVtZW50IHRoYXQgaXMgc21hbGxlciB0aGFuIG9yIGdyZWF0ZXIgdGhhbiB0aGUgb25lIHdlIGFyZVxuICogICAgIHNlYXJjaGluZyBmb3IsIHJlc3BlY3RpdmVseSwgaWYgdGhlIGV4YWN0IGVsZW1lbnQgY2Fubm90IGJlIGZvdW5kLlxuICovXG5mdW5jdGlvbiByZWN1cnNpdmVTZWFyY2goYUxvdywgYUhpZ2gsIGFOZWVkbGUsIGFIYXlzdGFjaywgYUNvbXBhcmUsIGFCaWFzKSB7XG4gIC8vIFRoaXMgZnVuY3Rpb24gdGVybWluYXRlcyB3aGVuIG9uZSBvZiB0aGUgZm9sbG93aW5nIGlzIHRydWU6XG4gIC8vXG4gIC8vICAgMS4gV2UgZmluZCB0aGUgZXhhY3QgZWxlbWVudCB3ZSBhcmUgbG9va2luZyBmb3IuXG4gIC8vXG4gIC8vICAgMi4gV2UgZGlkIG5vdCBmaW5kIHRoZSBleGFjdCBlbGVtZW50LCBidXQgd2UgY2FuIHJldHVybiB0aGUgaW5kZXggb2ZcbiAgLy8gICAgICB0aGUgbmV4dC1jbG9zZXN0IGVsZW1lbnQuXG4gIC8vXG4gIC8vICAgMy4gV2UgZGlkIG5vdCBmaW5kIHRoZSBleGFjdCBlbGVtZW50LCBhbmQgdGhlcmUgaXMgbm8gbmV4dC1jbG9zZXN0XG4gIC8vICAgICAgZWxlbWVudCB0aGFuIHRoZSBvbmUgd2UgYXJlIHNlYXJjaGluZyBmb3IsIHNvIHdlIHJldHVybiAtMS5cbiAgdmFyIG1pZCA9IE1hdGguZmxvb3IoKGFIaWdoIC0gYUxvdykgLyAyKSArIGFMb3c7XG4gIHZhciBjbXAgPSBhQ29tcGFyZShhTmVlZGxlLCBhSGF5c3RhY2tbbWlkXSwgdHJ1ZSk7XG4gIGlmIChjbXAgPT09IDApIHtcbiAgICAvLyBGb3VuZCB0aGUgZWxlbWVudCB3ZSBhcmUgbG9va2luZyBmb3IuXG4gICAgcmV0dXJuIG1pZDtcbiAgfVxuICBlbHNlIGlmIChjbXAgPiAwKSB7XG4gICAgLy8gT3VyIG5lZWRsZSBpcyBncmVhdGVyIHRoYW4gYUhheXN0YWNrW21pZF0uXG4gICAgaWYgKGFIaWdoIC0gbWlkID4gMSkge1xuICAgICAgLy8gVGhlIGVsZW1lbnQgaXMgaW4gdGhlIHVwcGVyIGhhbGYuXG4gICAgICByZXR1cm4gcmVjdXJzaXZlU2VhcmNoKG1pZCwgYUhpZ2gsIGFOZWVkbGUsIGFIYXlzdGFjaywgYUNvbXBhcmUsIGFCaWFzKTtcbiAgICB9XG5cbiAgICAvLyBUaGUgZXhhY3QgbmVlZGxlIGVsZW1lbnQgd2FzIG5vdCBmb3VuZCBpbiB0aGlzIGhheXN0YWNrLiBEZXRlcm1pbmUgaWZcbiAgICAvLyB3ZSBhcmUgaW4gdGVybWluYXRpb24gY2FzZSAoMykgb3IgKDIpIGFuZCByZXR1cm4gdGhlIGFwcHJvcHJpYXRlIHRoaW5nLlxuICAgIGlmIChhQmlhcyA9PSBleHBvcnRzLkxFQVNUX1VQUEVSX0JPVU5EKSB7XG4gICAgICByZXR1cm4gYUhpZ2ggPCBhSGF5c3RhY2subGVuZ3RoID8gYUhpZ2ggOiAtMTtcbiAgICB9IGVsc2Uge1xuICAgICAgcmV0dXJuIG1pZDtcbiAgICB9XG4gIH1cbiAgZWxzZSB7XG4gICAgLy8gT3VyIG5lZWRsZSBpcyBsZXNzIHRoYW4gYUhheXN0YWNrW21pZF0uXG4gICAgaWYgKG1pZCAtIGFMb3cgPiAxKSB7XG4gICAgICAvLyBUaGUgZWxlbWVudCBpcyBpbiB0aGUgbG93ZXIgaGFsZi5cbiAgICAgIHJldHVybiByZWN1cnNpdmVTZWFyY2goYUxvdywgbWlkLCBhTmVlZGxlLCBhSGF5c3RhY2ssIGFDb21wYXJlLCBhQmlhcyk7XG4gICAgfVxuXG4gICAgLy8gd2UgYXJlIGluIHRlcm1pbmF0aW9uIGNhc2UgKDMpIG9yICgyKSBhbmQgcmV0dXJuIHRoZSBhcHByb3ByaWF0ZSB0aGluZy5cbiAgICBpZiAoYUJpYXMgPT0gZXhwb3J0cy5MRUFTVF9VUFBFUl9CT1VORCkge1xuICAgICAgcmV0dXJuIG1pZDtcbiAgICB9IGVsc2Uge1xuICAgICAgcmV0dXJuIGFMb3cgPCAwID8gLTEgOiBhTG93O1xuICAgIH1cbiAgfVxufVxuXG4vKipcbiAqIFRoaXMgaXMgYW4gaW1wbGVtZW50YXRpb24gb2YgYmluYXJ5IHNlYXJjaCB3aGljaCB3aWxsIGFsd2F5cyB0cnkgYW5kIHJldHVyblxuICogdGhlIGluZGV4IG9mIHRoZSBjbG9zZXN0IGVsZW1lbnQgaWYgdGhlcmUgaXMgbm8gZXhhY3QgaGl0LiBUaGlzIGlzIGJlY2F1c2VcbiAqIG1hcHBpbmdzIGJldHdlZW4gb3JpZ2luYWwgYW5kIGdlbmVyYXRlZCBsaW5lL2NvbCBwYWlycyBhcmUgc2luZ2xlIHBvaW50cyxcbiAqIGFuZCB0aGVyZSBpcyBhbiBpbXBsaWNpdCByZWdpb24gYmV0d2VlbiBlYWNoIG9mIHRoZW0sIHNvIGEgbWlzcyBqdXN0IG1lYW5zXG4gKiB0aGF0IHlvdSBhcmVuJ3Qgb24gdGhlIHZlcnkgc3RhcnQgb2YgYSByZWdpb24uXG4gKlxuICogQHBhcmFtIGFOZWVkbGUgVGhlIGVsZW1lbnQgeW91IGFyZSBsb29raW5nIGZvci5cbiAqIEBwYXJhbSBhSGF5c3RhY2sgVGhlIGFycmF5IHRoYXQgaXMgYmVpbmcgc2VhcmNoZWQuXG4gKiBAcGFyYW0gYUNvbXBhcmUgQSBmdW5jdGlvbiB3aGljaCB0YWtlcyB0aGUgbmVlZGxlIGFuZCBhbiBlbGVtZW50IGluIHRoZVxuICogICAgIGFycmF5IGFuZCByZXR1cm5zIC0xLCAwLCBvciAxIGRlcGVuZGluZyBvbiB3aGV0aGVyIHRoZSBuZWVkbGUgaXMgbGVzc1xuICogICAgIHRoYW4sIGVxdWFsIHRvLCBvciBncmVhdGVyIHRoYW4gdGhlIGVsZW1lbnQsIHJlc3BlY3RpdmVseS5cbiAqIEBwYXJhbSBhQmlhcyBFaXRoZXIgJ2JpbmFyeVNlYXJjaC5HUkVBVEVTVF9MT1dFUl9CT1VORCcgb3JcbiAqICAgICAnYmluYXJ5U2VhcmNoLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnYmluYXJ5U2VhcmNoLkdSRUFURVNUX0xPV0VSX0JPVU5EJy5cbiAqL1xuZXhwb3J0cy5zZWFyY2ggPSBmdW5jdGlvbiBzZWFyY2goYU5lZWRsZSwgYUhheXN0YWNrLCBhQ29tcGFyZSwgYUJpYXMpIHtcbiAgaWYgKGFIYXlzdGFjay5sZW5ndGggPT09IDApIHtcbiAgICByZXR1cm4gLTE7XG4gIH1cblxuICB2YXIgaW5kZXggPSByZWN1cnNpdmVTZWFyY2goLTEsIGFIYXlzdGFjay5sZW5ndGgsIGFOZWVkbGUsIGFIYXlzdGFjayxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGFDb21wYXJlLCBhQmlhcyB8fCBleHBvcnRzLkdSRUFURVNUX0xPV0VSX0JPVU5EKTtcbiAgaWYgKGluZGV4IDwgMCkge1xuICAgIHJldHVybiAtMTtcbiAgfVxuXG4gIC8vIFdlIGhhdmUgZm91bmQgZWl0aGVyIHRoZSBleGFjdCBlbGVtZW50LCBvciB0aGUgbmV4dC1jbG9zZXN0IGVsZW1lbnQgdGhhblxuICAvLyB0aGUgb25lIHdlIGFyZSBzZWFyY2hpbmcgZm9yLiBIb3dldmVyLCB0aGVyZSBtYXkgYmUgbW9yZSB0aGFuIG9uZSBzdWNoXG4gIC8vIGVsZW1lbnQuIE1ha2Ugc3VyZSB3ZSBhbHdheXMgcmV0dXJuIHRoZSBzbWFsbGVzdCBvZiB0aGVzZS5cbiAgd2hpbGUgKGluZGV4IC0gMSA+PSAwKSB7XG4gICAgaWYgKGFDb21wYXJlKGFIYXlzdGFja1tpbmRleF0sIGFIYXlzdGFja1tpbmRleCAtIDFdLCB0cnVlKSAhPT0gMCkge1xuICAgICAgYnJlYWs7XG4gICAgfVxuICAgIC0taW5kZXg7XG4gIH1cblxuICByZXR1cm4gaW5kZXg7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvYmluYXJ5LXNlYXJjaC5qc1xuLy8gbW9kdWxlIGlkID0gOFxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbi8vIEl0IHR1cm5zIG91dCB0aGF0IHNvbWUgKG1vc3Q/KSBKYXZhU2NyaXB0IGVuZ2luZXMgZG9uJ3Qgc2VsZi1ob3N0XG4vLyBgQXJyYXkucHJvdG90eXBlLnNvcnRgLiBUaGlzIG1ha2VzIHNlbnNlIGJlY2F1c2UgQysrIHdpbGwgbGlrZWx5IHJlbWFpblxuLy8gZmFzdGVyIHRoYW4gSlMgd2hlbiBkb2luZyByYXcgQ1BVLWludGVuc2l2ZSBzb3J0aW5nLiBIb3dldmVyLCB3aGVuIHVzaW5nIGFcbi8vIGN1c3RvbSBjb21wYXJhdG9yIGZ1bmN0aW9uLCBjYWxsaW5nIGJhY2sgYW5kIGZvcnRoIGJldHdlZW4gdGhlIFZNJ3MgQysrIGFuZFxuLy8gSklUJ2QgSlMgaXMgcmF0aGVyIHNsb3cgKmFuZCogbG9zZXMgSklUIHR5cGUgaW5mb3JtYXRpb24sIHJlc3VsdGluZyBpblxuLy8gd29yc2UgZ2VuZXJhdGVkIGNvZGUgZm9yIHRoZSBjb21wYXJhdG9yIGZ1bmN0aW9uIHRoYW4gd291bGQgYmUgb3B0aW1hbC4gSW5cbi8vIGZhY3QsIHdoZW4gc29ydGluZyB3aXRoIGEgY29tcGFyYXRvciwgdGhlc2UgY29zdHMgb3V0d2VpZ2ggdGhlIGJlbmVmaXRzIG9mXG4vLyBzb3J0aW5nIGluIEMrKy4gQnkgdXNpbmcgb3VyIG93biBKUy1pbXBsZW1lbnRlZCBRdWljayBTb3J0IChiZWxvdyksIHdlIGdldFxuLy8gYSB+MzUwMG1zIG1lYW4gc3BlZWQtdXAgaW4gYGJlbmNoL2JlbmNoLmh0bWxgLlxuXG4vKipcbiAqIFN3YXAgdGhlIGVsZW1lbnRzIGluZGV4ZWQgYnkgYHhgIGFuZCBgeWAgaW4gdGhlIGFycmF5IGBhcnlgLlxuICpcbiAqIEBwYXJhbSB7QXJyYXl9IGFyeVxuICogICAgICAgIFRoZSBhcnJheS5cbiAqIEBwYXJhbSB7TnVtYmVyfSB4XG4gKiAgICAgICAgVGhlIGluZGV4IG9mIHRoZSBmaXJzdCBpdGVtLlxuICogQHBhcmFtIHtOdW1iZXJ9IHlcbiAqICAgICAgICBUaGUgaW5kZXggb2YgdGhlIHNlY29uZCBpdGVtLlxuICovXG5mdW5jdGlvbiBzd2FwKGFyeSwgeCwgeSkge1xuICB2YXIgdGVtcCA9IGFyeVt4XTtcbiAgYXJ5W3hdID0gYXJ5W3ldO1xuICBhcnlbeV0gPSB0ZW1wO1xufVxuXG4vKipcbiAqIFJldHVybnMgYSByYW5kb20gaW50ZWdlciB3aXRoaW4gdGhlIHJhbmdlIGBsb3cgLi4gaGlnaGAgaW5jbHVzaXZlLlxuICpcbiAqIEBwYXJhbSB7TnVtYmVyfSBsb3dcbiAqICAgICAgICBUaGUgbG93ZXIgYm91bmQgb24gdGhlIHJhbmdlLlxuICogQHBhcmFtIHtOdW1iZXJ9IGhpZ2hcbiAqICAgICAgICBUaGUgdXBwZXIgYm91bmQgb24gdGhlIHJhbmdlLlxuICovXG5mdW5jdGlvbiByYW5kb21JbnRJblJhbmdlKGxvdywgaGlnaCkge1xuICByZXR1cm4gTWF0aC5yb3VuZChsb3cgKyAoTWF0aC5yYW5kb20oKSAqIChoaWdoIC0gbG93KSkpO1xufVxuXG4vKipcbiAqIFRoZSBRdWljayBTb3J0IGFsZ29yaXRobS5cbiAqXG4gKiBAcGFyYW0ge0FycmF5fSBhcnlcbiAqICAgICAgICBBbiBhcnJheSB0byBzb3J0LlxuICogQHBhcmFtIHtmdW5jdGlvbn0gY29tcGFyYXRvclxuICogICAgICAgIEZ1bmN0aW9uIHRvIHVzZSB0byBjb21wYXJlIHR3byBpdGVtcy5cbiAqIEBwYXJhbSB7TnVtYmVyfSBwXG4gKiAgICAgICAgU3RhcnQgaW5kZXggb2YgdGhlIGFycmF5XG4gKiBAcGFyYW0ge051bWJlcn0gclxuICogICAgICAgIEVuZCBpbmRleCBvZiB0aGUgYXJyYXlcbiAqL1xuZnVuY3Rpb24gZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBwLCByKSB7XG4gIC8vIElmIG91ciBsb3dlciBib3VuZCBpcyBsZXNzIHRoYW4gb3VyIHVwcGVyIGJvdW5kLCB3ZSAoMSkgcGFydGl0aW9uIHRoZVxuICAvLyBhcnJheSBpbnRvIHR3byBwaWVjZXMgYW5kICgyKSByZWN1cnNlIG9uIGVhY2ggaGFsZi4gSWYgaXQgaXMgbm90LCB0aGlzIGlzXG4gIC8vIHRoZSBlbXB0eSBhcnJheSBhbmQgb3VyIGJhc2UgY2FzZS5cblxuICBpZiAocCA8IHIpIHtcbiAgICAvLyAoMSkgUGFydGl0aW9uaW5nLlxuICAgIC8vXG4gICAgLy8gVGhlIHBhcnRpdGlvbmluZyBjaG9vc2VzIGEgcGl2b3QgYmV0d2VlbiBgcGAgYW5kIGByYCBhbmQgbW92ZXMgYWxsXG4gICAgLy8gZWxlbWVudHMgdGhhdCBhcmUgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBwaXZvdCB0byB0aGUgYmVmb3JlIGl0LCBhbmRcbiAgICAvLyBhbGwgdGhlIGVsZW1lbnRzIHRoYXQgYXJlIGdyZWF0ZXIgdGhhbiBpdCBhZnRlciBpdC4gVGhlIGVmZmVjdCBpcyB0aGF0XG4gICAgLy8gb25jZSBwYXJ0aXRpb24gaXMgZG9uZSwgdGhlIHBpdm90IGlzIGluIHRoZSBleGFjdCBwbGFjZSBpdCB3aWxsIGJlIHdoZW5cbiAgICAvLyB0aGUgYXJyYXkgaXMgcHV0IGluIHNvcnRlZCBvcmRlciwgYW5kIGl0IHdpbGwgbm90IG5lZWQgdG8gYmUgbW92ZWRcbiAgICAvLyBhZ2Fpbi4gVGhpcyBydW5zIGluIE8obikgdGltZS5cblxuICAgIC8vIEFsd2F5cyBjaG9vc2UgYSByYW5kb20gcGl2b3Qgc28gdGhhdCBhbiBpbnB1dCBhcnJheSB3aGljaCBpcyByZXZlcnNlXG4gICAgLy8gc29ydGVkIGRvZXMgbm90IGNhdXNlIE8obl4yKSBydW5uaW5nIHRpbWUuXG4gICAgdmFyIHBpdm90SW5kZXggPSByYW5kb21JbnRJblJhbmdlKHAsIHIpO1xuICAgIHZhciBpID0gcCAtIDE7XG5cbiAgICBzd2FwKGFyeSwgcGl2b3RJbmRleCwgcik7XG4gICAgdmFyIHBpdm90ID0gYXJ5W3JdO1xuXG4gICAgLy8gSW1tZWRpYXRlbHkgYWZ0ZXIgYGpgIGlzIGluY3JlbWVudGVkIGluIHRoaXMgbG9vcCwgdGhlIGZvbGxvd2luZyBob2xkXG4gICAgLy8gdHJ1ZTpcbiAgICAvL1xuICAgIC8vICAgKiBFdmVyeSBlbGVtZW50IGluIGBhcnlbcCAuLiBpXWAgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBwaXZvdC5cbiAgICAvL1xuICAgIC8vICAgKiBFdmVyeSBlbGVtZW50IGluIGBhcnlbaSsxIC4uIGotMV1gIGlzIGdyZWF0ZXIgdGhhbiB0aGUgcGl2b3QuXG4gICAgZm9yICh2YXIgaiA9IHA7IGogPCByOyBqKyspIHtcbiAgICAgIGlmIChjb21wYXJhdG9yKGFyeVtqXSwgcGl2b3QpIDw9IDApIHtcbiAgICAgICAgaSArPSAxO1xuICAgICAgICBzd2FwKGFyeSwgaSwgaik7XG4gICAgICB9XG4gICAgfVxuXG4gICAgc3dhcChhcnksIGkgKyAxLCBqKTtcbiAgICB2YXIgcSA9IGkgKyAxO1xuXG4gICAgLy8gKDIpIFJlY3Vyc2Ugb24gZWFjaCBoYWxmLlxuXG4gICAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBwLCBxIC0gMSk7XG4gICAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBxICsgMSwgcik7XG4gIH1cbn1cblxuLyoqXG4gKiBTb3J0IHRoZSBnaXZlbiBhcnJheSBpbi1wbGFjZSB3aXRoIHRoZSBnaXZlbiBjb21wYXJhdG9yIGZ1bmN0aW9uLlxuICpcbiAqIEBwYXJhbSB7QXJyYXl9IGFyeVxuICogICAgICAgIEFuIGFycmF5IHRvIHNvcnQuXG4gKiBAcGFyYW0ge2Z1bmN0aW9ufSBjb21wYXJhdG9yXG4gKiAgICAgICAgRnVuY3Rpb24gdG8gdXNlIHRvIGNvbXBhcmUgdHdvIGl0ZW1zLlxuICovXG5leHBvcnRzLnF1aWNrU29ydCA9IGZ1bmN0aW9uIChhcnksIGNvbXBhcmF0b3IpIHtcbiAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCAwLCBhcnkubGVuZ3RoIC0gMSk7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvcXVpY2stc29ydC5qc1xuLy8gbW9kdWxlIGlkID0gOVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbnZhciBTb3VyY2VNYXBHZW5lcmF0b3IgPSByZXF1aXJlKCcuL3NvdXJjZS1tYXAtZ2VuZXJhdG9yJykuU291cmNlTWFwR2VuZXJhdG9yO1xudmFyIHV0aWwgPSByZXF1aXJlKCcuL3V0aWwnKTtcblxuLy8gTWF0Y2hlcyBhIFdpbmRvd3Mtc3R5bGUgYFxcclxcbmAgbmV3bGluZSBvciBhIGBcXG5gIG5ld2xpbmUgdXNlZCBieSBhbGwgb3RoZXJcbi8vIG9wZXJhdGluZyBzeXN0ZW1zIHRoZXNlIGRheXMgKGNhcHR1cmluZyB0aGUgcmVzdWx0KS5cbnZhciBSRUdFWF9ORVdMSU5FID0gLyhcXHI/XFxuKS87XG5cbi8vIE5ld2xpbmUgY2hhcmFjdGVyIGNvZGUgZm9yIGNoYXJDb2RlQXQoKSBjb21wYXJpc29uc1xudmFyIE5FV0xJTkVfQ09ERSA9IDEwO1xuXG4vLyBQcml2YXRlIHN5bWJvbCBmb3IgaWRlbnRpZnlpbmcgYFNvdXJjZU5vZGVgcyB3aGVuIG11bHRpcGxlIHZlcnNpb25zIG9mXG4vLyB0aGUgc291cmNlLW1hcCBsaWJyYXJ5IGFyZSBsb2FkZWQuIFRoaXMgTVVTVCBOT1QgQ0hBTkdFIGFjcm9zc1xuLy8gdmVyc2lvbnMhXG52YXIgaXNTb3VyY2VOb2RlID0gXCIkJCRpc1NvdXJjZU5vZGUkJCRcIjtcblxuLyoqXG4gKiBTb3VyY2VOb2RlcyBwcm92aWRlIGEgd2F5IHRvIGFic3RyYWN0IG92ZXIgaW50ZXJwb2xhdGluZy9jb25jYXRlbmF0aW5nXG4gKiBzbmlwcGV0cyBvZiBnZW5lcmF0ZWQgSmF2YVNjcmlwdCBzb3VyY2UgY29kZSB3aGlsZSBtYWludGFpbmluZyB0aGUgbGluZSBhbmRcbiAqIGNvbHVtbiBpbmZvcm1hdGlvbiBhc3NvY2lhdGVkIHdpdGggdGhlIG9yaWdpbmFsIHNvdXJjZSBjb2RlLlxuICpcbiAqIEBwYXJhbSBhTGluZSBUaGUgb3JpZ2luYWwgbGluZSBudW1iZXIuXG4gKiBAcGFyYW0gYUNvbHVtbiBUaGUgb3JpZ2luYWwgY29sdW1uIG51bWJlci5cbiAqIEBwYXJhbSBhU291cmNlIFRoZSBvcmlnaW5hbCBzb3VyY2UncyBmaWxlbmFtZS5cbiAqIEBwYXJhbSBhQ2h1bmtzIE9wdGlvbmFsLiBBbiBhcnJheSBvZiBzdHJpbmdzIHdoaWNoIGFyZSBzbmlwcGV0cyBvZlxuICogICAgICAgIGdlbmVyYXRlZCBKUywgb3Igb3RoZXIgU291cmNlTm9kZXMuXG4gKiBAcGFyYW0gYU5hbWUgVGhlIG9yaWdpbmFsIGlkZW50aWZpZXIuXG4gKi9cbmZ1bmN0aW9uIFNvdXJjZU5vZGUoYUxpbmUsIGFDb2x1bW4sIGFTb3VyY2UsIGFDaHVua3MsIGFOYW1lKSB7XG4gIHRoaXMuY2hpbGRyZW4gPSBbXTtcbiAgdGhpcy5zb3VyY2VDb250ZW50cyA9IHt9O1xuICB0aGlzLmxpbmUgPSBhTGluZSA9PSBudWxsID8gbnVsbCA6IGFMaW5lO1xuICB0aGlzLmNvbHVtbiA9IGFDb2x1bW4gPT0gbnVsbCA/IG51bGwgOiBhQ29sdW1uO1xuICB0aGlzLnNvdXJjZSA9IGFTb3VyY2UgPT0gbnVsbCA/IG51bGwgOiBhU291cmNlO1xuICB0aGlzLm5hbWUgPSBhTmFtZSA9PSBudWxsID8gbnVsbCA6IGFOYW1lO1xuICB0aGlzW2lzU291cmNlTm9kZV0gPSB0cnVlO1xuICBpZiAoYUNodW5rcyAhPSBudWxsKSB0aGlzLmFkZChhQ2h1bmtzKTtcbn1cblxuLyoqXG4gKiBDcmVhdGVzIGEgU291cmNlTm9kZSBmcm9tIGdlbmVyYXRlZCBjb2RlIGFuZCBhIFNvdXJjZU1hcENvbnN1bWVyLlxuICpcbiAqIEBwYXJhbSBhR2VuZXJhdGVkQ29kZSBUaGUgZ2VuZXJhdGVkIGNvZGVcbiAqIEBwYXJhbSBhU291cmNlTWFwQ29uc3VtZXIgVGhlIFNvdXJjZU1hcCBmb3IgdGhlIGdlbmVyYXRlZCBjb2RlXG4gKiBAcGFyYW0gYVJlbGF0aXZlUGF0aCBPcHRpb25hbC4gVGhlIHBhdGggdGhhdCByZWxhdGl2ZSBzb3VyY2VzIGluIHRoZVxuICogICAgICAgIFNvdXJjZU1hcENvbnN1bWVyIHNob3VsZCBiZSByZWxhdGl2ZSB0by5cbiAqL1xuU291cmNlTm9kZS5mcm9tU3RyaW5nV2l0aFNvdXJjZU1hcCA9XG4gIGZ1bmN0aW9uIFNvdXJjZU5vZGVfZnJvbVN0cmluZ1dpdGhTb3VyY2VNYXAoYUdlbmVyYXRlZENvZGUsIGFTb3VyY2VNYXBDb25zdW1lciwgYVJlbGF0aXZlUGF0aCkge1xuICAgIC8vIFRoZSBTb3VyY2VOb2RlIHdlIHdhbnQgdG8gZmlsbCB3aXRoIHRoZSBnZW5lcmF0ZWQgY29kZVxuICAgIC8vIGFuZCB0aGUgU291cmNlTWFwXG4gICAgdmFyIG5vZGUgPSBuZXcgU291cmNlTm9kZSgpO1xuXG4gICAgLy8gQWxsIGV2ZW4gaW5kaWNlcyBvZiB0aGlzIGFycmF5IGFyZSBvbmUgbGluZSBvZiB0aGUgZ2VuZXJhdGVkIGNvZGUsXG4gICAgLy8gd2hpbGUgYWxsIG9kZCBpbmRpY2VzIGFyZSB0aGUgbmV3bGluZXMgYmV0d2VlbiB0d28gYWRqYWNlbnQgbGluZXNcbiAgICAvLyAoc2luY2UgYFJFR0VYX05FV0xJTkVgIGNhcHR1cmVzIGl0cyBtYXRjaCkuXG4gICAgLy8gUHJvY2Vzc2VkIGZyYWdtZW50cyBhcmUgYWNjZXNzZWQgYnkgY2FsbGluZyBgc2hpZnROZXh0TGluZWAuXG4gICAgdmFyIHJlbWFpbmluZ0xpbmVzID0gYUdlbmVyYXRlZENvZGUuc3BsaXQoUkVHRVhfTkVXTElORSk7XG4gICAgdmFyIHJlbWFpbmluZ0xpbmVzSW5kZXggPSAwO1xuICAgIHZhciBzaGlmdE5leHRMaW5lID0gZnVuY3Rpb24oKSB7XG4gICAgICB2YXIgbGluZUNvbnRlbnRzID0gZ2V0TmV4dExpbmUoKTtcbiAgICAgIC8vIFRoZSBsYXN0IGxpbmUgb2YgYSBmaWxlIG1pZ2h0IG5vdCBoYXZlIGEgbmV3bGluZS5cbiAgICAgIHZhciBuZXdMaW5lID0gZ2V0TmV4dExpbmUoKSB8fCBcIlwiO1xuICAgICAgcmV0dXJuIGxpbmVDb250ZW50cyArIG5ld0xpbmU7XG5cbiAgICAgIGZ1bmN0aW9uIGdldE5leHRMaW5lKCkge1xuICAgICAgICByZXR1cm4gcmVtYWluaW5nTGluZXNJbmRleCA8IHJlbWFpbmluZ0xpbmVzLmxlbmd0aCA/XG4gICAgICAgICAgICByZW1haW5pbmdMaW5lc1tyZW1haW5pbmdMaW5lc0luZGV4KytdIDogdW5kZWZpbmVkO1xuICAgICAgfVxuICAgIH07XG5cbiAgICAvLyBXZSBuZWVkIHRvIHJlbWVtYmVyIHRoZSBwb3NpdGlvbiBvZiBcInJlbWFpbmluZ0xpbmVzXCJcbiAgICB2YXIgbGFzdEdlbmVyYXRlZExpbmUgPSAxLCBsYXN0R2VuZXJhdGVkQ29sdW1uID0gMDtcblxuICAgIC8vIFRoZSBnZW5lcmF0ZSBTb3VyY2VOb2RlcyB3ZSBuZWVkIGEgY29kZSByYW5nZS5cbiAgICAvLyBUbyBleHRyYWN0IGl0IGN1cnJlbnQgYW5kIGxhc3QgbWFwcGluZyBpcyB1c2VkLlxuICAgIC8vIEhlcmUgd2Ugc3RvcmUgdGhlIGxhc3QgbWFwcGluZy5cbiAgICB2YXIgbGFzdE1hcHBpbmcgPSBudWxsO1xuXG4gICAgYVNvdXJjZU1hcENvbnN1bWVyLmVhY2hNYXBwaW5nKGZ1bmN0aW9uIChtYXBwaW5nKSB7XG4gICAgICBpZiAobGFzdE1hcHBpbmcgIT09IG51bGwpIHtcbiAgICAgICAgLy8gV2UgYWRkIHRoZSBjb2RlIGZyb20gXCJsYXN0TWFwcGluZ1wiIHRvIFwibWFwcGluZ1wiOlxuICAgICAgICAvLyBGaXJzdCBjaGVjayBpZiB0aGVyZSBpcyBhIG5ldyBsaW5lIGluIGJldHdlZW4uXG4gICAgICAgIGlmIChsYXN0R2VuZXJhdGVkTGluZSA8IG1hcHBpbmcuZ2VuZXJhdGVkTGluZSkge1xuICAgICAgICAgIC8vIEFzc29jaWF0ZSBmaXJzdCBsaW5lIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgICAgYWRkTWFwcGluZ1dpdGhDb2RlKGxhc3RNYXBwaW5nLCBzaGlmdE5leHRMaW5lKCkpO1xuICAgICAgICAgIGxhc3RHZW5lcmF0ZWRMaW5lKys7XG4gICAgICAgICAgbGFzdEdlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgICAgICAgLy8gVGhlIHJlbWFpbmluZyBjb2RlIGlzIGFkZGVkIHdpdGhvdXQgbWFwcGluZ1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIC8vIFRoZXJlIGlzIG5vIG5ldyBsaW5lIGluIGJldHdlZW4uXG4gICAgICAgICAgLy8gQXNzb2NpYXRlIHRoZSBjb2RlIGJldHdlZW4gXCJsYXN0R2VuZXJhdGVkQ29sdW1uXCIgYW5kXG4gICAgICAgICAgLy8gXCJtYXBwaW5nLmdlbmVyYXRlZENvbHVtblwiIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgICAgdmFyIG5leHRMaW5lID0gcmVtYWluaW5nTGluZXNbcmVtYWluaW5nTGluZXNJbmRleF0gfHwgJyc7XG4gICAgICAgICAgdmFyIGNvZGUgPSBuZXh0TGluZS5zdWJzdHIoMCwgbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4gLVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxhc3RHZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgICAgIHJlbWFpbmluZ0xpbmVzW3JlbWFpbmluZ0xpbmVzSW5kZXhdID0gbmV4dExpbmUuc3Vic3RyKG1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uIC1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uKTtcbiAgICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uID0gbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW47XG4gICAgICAgICAgYWRkTWFwcGluZ1dpdGhDb2RlKGxhc3RNYXBwaW5nLCBjb2RlKTtcbiAgICAgICAgICAvLyBObyBtb3JlIHJlbWFpbmluZyBjb2RlLCBjb250aW51ZVxuICAgICAgICAgIGxhc3RNYXBwaW5nID0gbWFwcGluZztcbiAgICAgICAgICByZXR1cm47XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICAgIC8vIFdlIGFkZCB0aGUgZ2VuZXJhdGVkIGNvZGUgdW50aWwgdGhlIGZpcnN0IG1hcHBpbmdcbiAgICAgIC8vIHRvIHRoZSBTb3VyY2VOb2RlIHdpdGhvdXQgYW55IG1hcHBpbmcuXG4gICAgICAvLyBFYWNoIGxpbmUgaXMgYWRkZWQgYXMgc2VwYXJhdGUgc3RyaW5nLlxuICAgICAgd2hpbGUgKGxhc3RHZW5lcmF0ZWRMaW5lIDwgbWFwcGluZy5nZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgIG5vZGUuYWRkKHNoaWZ0TmV4dExpbmUoKSk7XG4gICAgICAgIGxhc3RHZW5lcmF0ZWRMaW5lKys7XG4gICAgICB9XG4gICAgICBpZiAobGFzdEdlbmVyYXRlZENvbHVtbiA8IG1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uKSB7XG4gICAgICAgIHZhciBuZXh0TGluZSA9IHJlbWFpbmluZ0xpbmVzW3JlbWFpbmluZ0xpbmVzSW5kZXhdIHx8ICcnO1xuICAgICAgICBub2RlLmFkZChuZXh0TGluZS5zdWJzdHIoMCwgbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4pKTtcbiAgICAgICAgcmVtYWluaW5nTGluZXNbcmVtYWluaW5nTGluZXNJbmRleF0gPSBuZXh0TGluZS5zdWJzdHIobWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uID0gbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW47XG4gICAgICB9XG4gICAgICBsYXN0TWFwcGluZyA9IG1hcHBpbmc7XG4gICAgfSwgdGhpcyk7XG4gICAgLy8gV2UgaGF2ZSBwcm9jZXNzZWQgYWxsIG1hcHBpbmdzLlxuICAgIGlmIChyZW1haW5pbmdMaW5lc0luZGV4IDwgcmVtYWluaW5nTGluZXMubGVuZ3RoKSB7XG4gICAgICBpZiAobGFzdE1hcHBpbmcpIHtcbiAgICAgICAgLy8gQXNzb2NpYXRlIHRoZSByZW1haW5pbmcgY29kZSBpbiB0aGUgY3VycmVudCBsaW5lIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgIGFkZE1hcHBpbmdXaXRoQ29kZShsYXN0TWFwcGluZywgc2hpZnROZXh0TGluZSgpKTtcbiAgICAgIH1cbiAgICAgIC8vIGFuZCBhZGQgdGhlIHJlbWFpbmluZyBsaW5lcyB3aXRob3V0IGFueSBtYXBwaW5nXG4gICAgICBub2RlLmFkZChyZW1haW5pbmdMaW5lcy5zcGxpY2UocmVtYWluaW5nTGluZXNJbmRleCkuam9pbihcIlwiKSk7XG4gICAgfVxuXG4gICAgLy8gQ29weSBzb3VyY2VzQ29udGVudCBpbnRvIFNvdXJjZU5vZGVcbiAgICBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlcy5mb3JFYWNoKGZ1bmN0aW9uIChzb3VyY2VGaWxlKSB7XG4gICAgICB2YXIgY29udGVudCA9IGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKHNvdXJjZUZpbGUpO1xuICAgICAgaWYgKGNvbnRlbnQgIT0gbnVsbCkge1xuICAgICAgICBpZiAoYVJlbGF0aXZlUGF0aCAhPSBudWxsKSB7XG4gICAgICAgICAgc291cmNlRmlsZSA9IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBzb3VyY2VGaWxlKTtcbiAgICAgICAgfVxuICAgICAgICBub2RlLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSk7XG5cbiAgICByZXR1cm4gbm9kZTtcblxuICAgIGZ1bmN0aW9uIGFkZE1hcHBpbmdXaXRoQ29kZShtYXBwaW5nLCBjb2RlKSB7XG4gICAgICBpZiAobWFwcGluZyA9PT0gbnVsbCB8fCBtYXBwaW5nLnNvdXJjZSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIG5vZGUuYWRkKGNvZGUpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IGFSZWxhdGl2ZVBhdGhcbiAgICAgICAgICA/IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICA6IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBub2RlLmFkZChuZXcgU291cmNlTm9kZShtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBtYXBwaW5nLm5hbWUpKTtcbiAgICAgIH1cbiAgICB9XG4gIH07XG5cbi8qKlxuICogQWRkIGEgY2h1bmsgb2YgZ2VuZXJhdGVkIEpTIHRvIHRoaXMgc291cmNlIG5vZGUuXG4gKlxuICogQHBhcmFtIGFDaHVuayBBIHN0cmluZyBzbmlwcGV0IG9mIGdlbmVyYXRlZCBKUyBjb2RlLCBhbm90aGVyIGluc3RhbmNlIG9mXG4gKiAgICAgICAgU291cmNlTm9kZSwgb3IgYW4gYXJyYXkgd2hlcmUgZWFjaCBtZW1iZXIgaXMgb25lIG9mIHRob3NlIHRoaW5ncy5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUuYWRkID0gZnVuY3Rpb24gU291cmNlTm9kZV9hZGQoYUNodW5rKSB7XG4gIGlmIChBcnJheS5pc0FycmF5KGFDaHVuaykpIHtcbiAgICBhQ2h1bmsuZm9yRWFjaChmdW5jdGlvbiAoY2h1bmspIHtcbiAgICAgIHRoaXMuYWRkKGNodW5rKTtcbiAgICB9LCB0aGlzKTtcbiAgfVxuICBlbHNlIGlmIChhQ2h1bmtbaXNTb3VyY2VOb2RlXSB8fCB0eXBlb2YgYUNodW5rID09PSBcInN0cmluZ1wiKSB7XG4gICAgaWYgKGFDaHVuaykge1xuICAgICAgdGhpcy5jaGlsZHJlbi5wdXNoKGFDaHVuayk7XG4gICAgfVxuICB9XG4gIGVsc2Uge1xuICAgIHRocm93IG5ldyBUeXBlRXJyb3IoXG4gICAgICBcIkV4cGVjdGVkIGEgU291cmNlTm9kZSwgc3RyaW5nLCBvciBhbiBhcnJheSBvZiBTb3VyY2VOb2RlcyBhbmQgc3RyaW5ncy4gR290IFwiICsgYUNodW5rXG4gICAgKTtcbiAgfVxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogQWRkIGEgY2h1bmsgb2YgZ2VuZXJhdGVkIEpTIHRvIHRoZSBiZWdpbm5pbmcgb2YgdGhpcyBzb3VyY2Ugbm9kZS5cbiAqXG4gKiBAcGFyYW0gYUNodW5rIEEgc3RyaW5nIHNuaXBwZXQgb2YgZ2VuZXJhdGVkIEpTIGNvZGUsIGFub3RoZXIgaW5zdGFuY2Ugb2ZcbiAqICAgICAgICBTb3VyY2VOb2RlLCBvciBhbiBhcnJheSB3aGVyZSBlYWNoIG1lbWJlciBpcyBvbmUgb2YgdGhvc2UgdGhpbmdzLlxuICovXG5Tb3VyY2VOb2RlLnByb3RvdHlwZS5wcmVwZW5kID0gZnVuY3Rpb24gU291cmNlTm9kZV9wcmVwZW5kKGFDaHVuaykge1xuICBpZiAoQXJyYXkuaXNBcnJheShhQ2h1bmspKSB7XG4gICAgZm9yICh2YXIgaSA9IGFDaHVuay5sZW5ndGgtMTsgaSA+PSAwOyBpLS0pIHtcbiAgICAgIHRoaXMucHJlcGVuZChhQ2h1bmtbaV0pO1xuICAgIH1cbiAgfVxuICBlbHNlIGlmIChhQ2h1bmtbaXNTb3VyY2VOb2RlXSB8fCB0eXBlb2YgYUNodW5rID09PSBcInN0cmluZ1wiKSB7XG4gICAgdGhpcy5jaGlsZHJlbi51bnNoaWZ0KGFDaHVuayk7XG4gIH1cbiAgZWxzZSB7XG4gICAgdGhyb3cgbmV3IFR5cGVFcnJvcihcbiAgICAgIFwiRXhwZWN0ZWQgYSBTb3VyY2VOb2RlLCBzdHJpbmcsIG9yIGFuIGFycmF5IG9mIFNvdXJjZU5vZGVzIGFuZCBzdHJpbmdzLiBHb3QgXCIgKyBhQ2h1bmtcbiAgICApO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBXYWxrIG92ZXIgdGhlIHRyZWUgb2YgSlMgc25pcHBldHMgaW4gdGhpcyBub2RlIGFuZCBpdHMgY2hpbGRyZW4uIFRoZVxuICogd2Fsa2luZyBmdW5jdGlvbiBpcyBjYWxsZWQgb25jZSBmb3IgZWFjaCBzbmlwcGV0IG9mIEpTIGFuZCBpcyBwYXNzZWQgdGhhdFxuICogc25pcHBldCBhbmQgdGhlIGl0cyBvcmlnaW5hbCBhc3NvY2lhdGVkIHNvdXJjZSdzIGxpbmUvY29sdW1uIGxvY2F0aW9uLlxuICpcbiAqIEBwYXJhbSBhRm4gVGhlIHRyYXZlcnNhbCBmdW5jdGlvbi5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUud2FsayA9IGZ1bmN0aW9uIFNvdXJjZU5vZGVfd2FsayhhRm4pIHtcbiAgdmFyIGNodW5rO1xuICBmb3IgKHZhciBpID0gMCwgbGVuID0gdGhpcy5jaGlsZHJlbi5sZW5ndGg7IGkgPCBsZW47IGkrKykge1xuICAgIGNodW5rID0gdGhpcy5jaGlsZHJlbltpXTtcbiAgICBpZiAoY2h1bmtbaXNTb3VyY2VOb2RlXSkge1xuICAgICAgY2h1bmsud2FsayhhRm4pO1xuICAgIH1cbiAgICBlbHNlIHtcbiAgICAgIGlmIChjaHVuayAhPT0gJycpIHtcbiAgICAgICAgYUZuKGNodW5rLCB7IHNvdXJjZTogdGhpcy5zb3VyY2UsXG4gICAgICAgICAgICAgICAgICAgICBsaW5lOiB0aGlzLmxpbmUsXG4gICAgICAgICAgICAgICAgICAgICBjb2x1bW46IHRoaXMuY29sdW1uLFxuICAgICAgICAgICAgICAgICAgICAgbmFtZTogdGhpcy5uYW1lIH0pO1xuICAgICAgfVxuICAgIH1cbiAgfVxufTtcblxuLyoqXG4gKiBMaWtlIGBTdHJpbmcucHJvdG90eXBlLmpvaW5gIGV4Y2VwdCBmb3IgU291cmNlTm9kZXMuIEluc2VydHMgYGFTdHJgIGJldHdlZW5cbiAqIGVhY2ggb2YgYHRoaXMuY2hpbGRyZW5gLlxuICpcbiAqIEBwYXJhbSBhU2VwIFRoZSBzZXBhcmF0b3IuXG4gKi9cblNvdXJjZU5vZGUucHJvdG90eXBlLmpvaW4gPSBmdW5jdGlvbiBTb3VyY2VOb2RlX2pvaW4oYVNlcCkge1xuICB2YXIgbmV3Q2hpbGRyZW47XG4gIHZhciBpO1xuICB2YXIgbGVuID0gdGhpcy5jaGlsZHJlbi5sZW5ndGg7XG4gIGlmIChsZW4gPiAwKSB7XG4gICAgbmV3Q2hpbGRyZW4gPSBbXTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgbGVuLTE7IGkrKykge1xuICAgICAgbmV3Q2hpbGRyZW4ucHVzaCh0aGlzLmNoaWxkcmVuW2ldKTtcbiAgICAgIG5ld0NoaWxkcmVuLnB1c2goYVNlcCk7XG4gICAgfVxuICAgIG5ld0NoaWxkcmVuLnB1c2godGhpcy5jaGlsZHJlbltpXSk7XG4gICAgdGhpcy5jaGlsZHJlbiA9IG5ld0NoaWxkcmVuO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBDYWxsIFN0cmluZy5wcm90b3R5cGUucmVwbGFjZSBvbiB0aGUgdmVyeSByaWdodC1tb3N0IHNvdXJjZSBzbmlwcGV0LiBVc2VmdWxcbiAqIGZvciB0cmltbWluZyB3aGl0ZXNwYWNlIGZyb20gdGhlIGVuZCBvZiBhIHNvdXJjZSBub2RlLCBldGMuXG4gKlxuICogQHBhcmFtIGFQYXR0ZXJuIFRoZSBwYXR0ZXJuIHRvIHJlcGxhY2UuXG4gKiBAcGFyYW0gYVJlcGxhY2VtZW50IFRoZSB0aGluZyB0byByZXBsYWNlIHRoZSBwYXR0ZXJuIHdpdGguXG4gKi9cblNvdXJjZU5vZGUucHJvdG90eXBlLnJlcGxhY2VSaWdodCA9IGZ1bmN0aW9uIFNvdXJjZU5vZGVfcmVwbGFjZVJpZ2h0KGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpIHtcbiAgdmFyIGxhc3RDaGlsZCA9IHRoaXMuY2hpbGRyZW5bdGhpcy5jaGlsZHJlbi5sZW5ndGggLSAxXTtcbiAgaWYgKGxhc3RDaGlsZFtpc1NvdXJjZU5vZGVdKSB7XG4gICAgbGFzdENoaWxkLnJlcGxhY2VSaWdodChhUGF0dGVybiwgYVJlcGxhY2VtZW50KTtcbiAgfVxuICBlbHNlIGlmICh0eXBlb2YgbGFzdENoaWxkID09PSAnc3RyaW5nJykge1xuICAgIHRoaXMuY2hpbGRyZW5bdGhpcy5jaGlsZHJlbi5sZW5ndGggLSAxXSA9IGxhc3RDaGlsZC5yZXBsYWNlKGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpO1xuICB9XG4gIGVsc2Uge1xuICAgIHRoaXMuY2hpbGRyZW4ucHVzaCgnJy5yZXBsYWNlKGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpKTtcbiAgfVxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogU2V0IHRoZSBzb3VyY2UgY29udGVudCBmb3IgYSBzb3VyY2UgZmlsZS4gVGhpcyB3aWxsIGJlIGFkZGVkIHRvIHRoZSBTb3VyY2VNYXBHZW5lcmF0b3JcbiAqIGluIHRoZSBzb3VyY2VzQ29udGVudCBmaWVsZC5cbiAqXG4gKiBAcGFyYW0gYVNvdXJjZUZpbGUgVGhlIGZpbGVuYW1lIG9mIHRoZSBzb3VyY2UgZmlsZVxuICogQHBhcmFtIGFTb3VyY2VDb250ZW50IFRoZSBjb250ZW50IG9mIHRoZSBzb3VyY2UgZmlsZVxuICovXG5Tb3VyY2VOb2RlLnByb3RvdHlwZS5zZXRTb3VyY2VDb250ZW50ID1cbiAgZnVuY3Rpb24gU291cmNlTm9kZV9zZXRTb3VyY2VDb250ZW50KGFTb3VyY2VGaWxlLCBhU291cmNlQ29udGVudCkge1xuICAgIHRoaXMuc291cmNlQ29udGVudHNbdXRpbC50b1NldFN0cmluZyhhU291cmNlRmlsZSldID0gYVNvdXJjZUNvbnRlbnQ7XG4gIH07XG5cbi8qKlxuICogV2FsayBvdmVyIHRoZSB0cmVlIG9mIFNvdXJjZU5vZGVzLiBUaGUgd2Fsa2luZyBmdW5jdGlvbiBpcyBjYWxsZWQgZm9yIGVhY2hcbiAqIHNvdXJjZSBmaWxlIGNvbnRlbnQgYW5kIGlzIHBhc3NlZCB0aGUgZmlsZW5hbWUgYW5kIHNvdXJjZSBjb250ZW50LlxuICpcbiAqIEBwYXJhbSBhRm4gVGhlIHRyYXZlcnNhbCBmdW5jdGlvbi5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUud2Fsa1NvdXJjZUNvbnRlbnRzID1cbiAgZnVuY3Rpb24gU291cmNlTm9kZV93YWxrU291cmNlQ29udGVudHMoYUZuKSB7XG4gICAgZm9yICh2YXIgaSA9IDAsIGxlbiA9IHRoaXMuY2hpbGRyZW4ubGVuZ3RoOyBpIDwgbGVuOyBpKyspIHtcbiAgICAgIGlmICh0aGlzLmNoaWxkcmVuW2ldW2lzU291cmNlTm9kZV0pIHtcbiAgICAgICAgdGhpcy5jaGlsZHJlbltpXS53YWxrU291cmNlQ29udGVudHMoYUZuKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICB2YXIgc291cmNlcyA9IE9iamVjdC5rZXlzKHRoaXMuc291cmNlQ29udGVudHMpO1xuICAgIGZvciAodmFyIGkgPSAwLCBsZW4gPSBzb3VyY2VzLmxlbmd0aDsgaSA8IGxlbjsgaSsrKSB7XG4gICAgICBhRm4odXRpbC5mcm9tU2V0U3RyaW5nKHNvdXJjZXNbaV0pLCB0aGlzLnNvdXJjZUNvbnRlbnRzW3NvdXJjZXNbaV1dKTtcbiAgICB9XG4gIH07XG5cbi8qKlxuICogUmV0dXJuIHRoZSBzdHJpbmcgcmVwcmVzZW50YXRpb24gb2YgdGhpcyBzb3VyY2Ugbm9kZS4gV2Fsa3Mgb3ZlciB0aGUgdHJlZVxuICogYW5kIGNvbmNhdGVuYXRlcyBhbGwgdGhlIHZhcmlvdXMgc25pcHBldHMgdG9nZXRoZXIgdG8gb25lIHN0cmluZy5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUudG9TdHJpbmcgPSBmdW5jdGlvbiBTb3VyY2VOb2RlX3RvU3RyaW5nKCkge1xuICB2YXIgc3RyID0gXCJcIjtcbiAgdGhpcy53YWxrKGZ1bmN0aW9uIChjaHVuaykge1xuICAgIHN0ciArPSBjaHVuaztcbiAgfSk7XG4gIHJldHVybiBzdHI7XG59O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIHN0cmluZyByZXByZXNlbnRhdGlvbiBvZiB0aGlzIHNvdXJjZSBub2RlIGFsb25nIHdpdGggYSBzb3VyY2VcbiAqIG1hcC5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUudG9TdHJpbmdXaXRoU291cmNlTWFwID0gZnVuY3Rpb24gU291cmNlTm9kZV90b1N0cmluZ1dpdGhTb3VyY2VNYXAoYUFyZ3MpIHtcbiAgdmFyIGdlbmVyYXRlZCA9IHtcbiAgICBjb2RlOiBcIlwiLFxuICAgIGxpbmU6IDEsXG4gICAgY29sdW1uOiAwXG4gIH07XG4gIHZhciBtYXAgPSBuZXcgU291cmNlTWFwR2VuZXJhdG9yKGFBcmdzKTtcbiAgdmFyIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgdmFyIGxhc3RPcmlnaW5hbFNvdXJjZSA9IG51bGw7XG4gIHZhciBsYXN0T3JpZ2luYWxMaW5lID0gbnVsbDtcbiAgdmFyIGxhc3RPcmlnaW5hbENvbHVtbiA9IG51bGw7XG4gIHZhciBsYXN0T3JpZ2luYWxOYW1lID0gbnVsbDtcbiAgdGhpcy53YWxrKGZ1bmN0aW9uIChjaHVuaywgb3JpZ2luYWwpIHtcbiAgICBnZW5lcmF0ZWQuY29kZSArPSBjaHVuaztcbiAgICBpZiAob3JpZ2luYWwuc291cmNlICE9PSBudWxsXG4gICAgICAgICYmIG9yaWdpbmFsLmxpbmUgIT09IG51bGxcbiAgICAgICAgJiYgb3JpZ2luYWwuY29sdW1uICE9PSBudWxsKSB7XG4gICAgICBpZihsYXN0T3JpZ2luYWxTb3VyY2UgIT09IG9yaWdpbmFsLnNvdXJjZVxuICAgICAgICAgfHwgbGFzdE9yaWdpbmFsTGluZSAhPT0gb3JpZ2luYWwubGluZVxuICAgICAgICAgfHwgbGFzdE9yaWdpbmFsQ29sdW1uICE9PSBvcmlnaW5hbC5jb2x1bW5cbiAgICAgICAgIHx8IGxhc3RPcmlnaW5hbE5hbWUgIT09IG9yaWdpbmFsLm5hbWUpIHtcbiAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgIHNvdXJjZTogb3JpZ2luYWwuc291cmNlLFxuICAgICAgICAgIG9yaWdpbmFsOiB7XG4gICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgY29sdW1uOiBvcmlnaW5hbC5jb2x1bW5cbiAgICAgICAgICB9LFxuICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgbGluZTogZ2VuZXJhdGVkLmxpbmUsXG4gICAgICAgICAgICBjb2x1bW46IGdlbmVyYXRlZC5jb2x1bW5cbiAgICAgICAgICB9LFxuICAgICAgICAgIG5hbWU6IG9yaWdpbmFsLm5hbWVcbiAgICAgICAgfSk7XG4gICAgICB9XG4gICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBvcmlnaW5hbC5zb3VyY2U7XG4gICAgICBsYXN0T3JpZ2luYWxMaW5lID0gb3JpZ2luYWwubGluZTtcbiAgICAgIGxhc3RPcmlnaW5hbENvbHVtbiA9IG9yaWdpbmFsLmNvbHVtbjtcbiAgICAgIGxhc3RPcmlnaW5hbE5hbWUgPSBvcmlnaW5hbC5uYW1lO1xuICAgICAgc291cmNlTWFwcGluZ0FjdGl2ZSA9IHRydWU7XG4gICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICBtYXAuYWRkTWFwcGluZyh7XG4gICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgIGxpbmU6IGdlbmVyYXRlZC5saW5lLFxuICAgICAgICAgIGNvbHVtbjogZ2VuZXJhdGVkLmNvbHVtblxuICAgICAgICB9XG4gICAgICB9KTtcbiAgICAgIGxhc3RPcmlnaW5hbFNvdXJjZSA9IG51bGw7XG4gICAgICBzb3VyY2VNYXBwaW5nQWN0aXZlID0gZmFsc2U7XG4gICAgfVxuICAgIGZvciAodmFyIGlkeCA9IDAsIGxlbmd0aCA9IGNodW5rLmxlbmd0aDsgaWR4IDwgbGVuZ3RoOyBpZHgrKykge1xuICAgICAgaWYgKGNodW5rLmNoYXJDb2RlQXQoaWR4KSA9PT0gTkVXTElORV9DT0RFKSB7XG4gICAgICAgIGdlbmVyYXRlZC5saW5lKys7XG4gICAgICAgIGdlbmVyYXRlZC5jb2x1bW4gPSAwO1xuICAgICAgICAvLyBNYXBwaW5ncyBlbmQgYXQgZW9sXG4gICAgICAgIGlmIChpZHggKyAxID09PSBsZW5ndGgpIHtcbiAgICAgICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBudWxsO1xuICAgICAgICAgIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgICAgICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgICAgc291cmNlOiBvcmlnaW5hbC5zb3VyY2UsXG4gICAgICAgICAgICBvcmlnaW5hbDoge1xuICAgICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgICBjb2x1bW46IG9yaWdpbmFsLmNvbHVtblxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWQubGluZSxcbiAgICAgICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWQuY29sdW1uXG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgbmFtZTogb3JpZ2luYWwubmFtZVxuICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBnZW5lcmF0ZWQuY29sdW1uKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcbiAgdGhpcy53YWxrU291cmNlQ29udGVudHMoZnVuY3Rpb24gKHNvdXJjZUZpbGUsIHNvdXJjZUNvbnRlbnQpIHtcbiAgICBtYXAuc2V0U291cmNlQ29udGVudChzb3VyY2VGaWxlLCBzb3VyY2VDb250ZW50KTtcbiAgfSk7XG5cbiAgcmV0dXJuIHsgY29kZTogZ2VuZXJhdGVkLmNvZGUsIG1hcDogbWFwIH07XG59O1xuXG5leHBvcnRzLlNvdXJjZU5vZGUgPSBTb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW5vZGUuanNcbi8vIG1vZHVsZSBpZCA9IDEwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCJdLCJzb3VyY2VSb290IjoiIn0= \ No newline at end of file diff --git a/node_modules/source-map/dist/source-map.js b/node_modules/source-map/dist/source-map.js new file mode 100644 index 0000000..b4eb087 --- /dev/null +++ b/node_modules/source-map/dist/source-map.js @@ -0,0 +1,3233 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * * Neither the name of Google Inc. 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 + * OWNER 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. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/node_modules/source-map/dist/source-map.min.js b/node_modules/source-map/dist/source-map.min.js new file mode 100644 index 0000000..c7c72da --- /dev/null +++ b/node_modules/source-map/dist/source-map.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.sourceMap=n():e.sourceMap=n()}(this,function(){return function(e){function n(t){if(r[t])return r[t].exports;var o=r[t]={exports:{},id:t,loaded:!1};return e[t].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=e,n.c=r,n.p="",n(0)}([function(e,n,r){n.SourceMapGenerator=r(1).SourceMapGenerator,n.SourceMapConsumer=r(7).SourceMapConsumer,n.SourceNode=r(10).SourceNode},function(e,n,r){function t(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new s,this._names=new s,this._mappings=new a,this._sourcesContents=null}var o=r(2),i=r(4),s=r(5).ArraySet,a=r(6).MappingList;t.prototype._version=3,t.fromSourceMap=function(e){var n=e.sourceRoot,r=new t({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(t.source=e.source,null!=n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(t.name=e.name)),r.addMapping(t)}),e.sources.forEach(function(t){var o=t;null!==n&&(o=i.relative(n,t)),r._sources.has(o)||r._sources.add(o);var s=e.sourceContentFor(t);null!=s&&r.setSourceContent(t,s)}),r},t.prototype.addMapping=function(e){var n=i.getArg(e,"generated"),r=i.getArg(e,"original",null),t=i.getArg(e,"source",null),o=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,t,o),null!=t&&(t=String(t),this._sources.has(t)||this._sources.add(t)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:t,name:o})},t.prototype.setSourceContent=function(e,n){var r=e;null!=this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),null!=n?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[i.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},t.prototype.applySourceMap=function(e,n,r){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=i.relative(o,t));var a=new s,u=new s;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var s=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=s.source&&(n.source=s.source,null!=r&&(n.source=i.join(r,n.source)),null!=o&&(n.source=i.relative(o,n.source)),n.originalLine=s.line,n.originalColumn=s.column,null!=s.name&&(n.name=s.name))}var l=n.source;null==l||a.has(l)||a.add(l);var c=n.name;null==c||u.has(c)||u.add(c)},this),this._sources=a,this._names=u,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=r&&(n=i.join(r,n)),null!=o&&(n=i.relative(o,n)),this.setSourceContent(n,t))},this)},t.prototype._validateMapping=function(e,n,r,t){if(n&&"number"!=typeof n.line&&"number"!=typeof n.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||n||r||t)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:t}))},t.prototype._serializeMappings=function(){for(var e,n,r,t,s=0,a=1,u=0,l=0,c=0,g=0,p="",h=this._mappings.toArray(),f=0,d=h.length;f0){if(!i.compareByGeneratedPositionsInflated(n,h[f-1]))continue;e+=","}e+=o.encode(n.generatedColumn-s),s=n.generatedColumn,null!=n.source&&(t=this._sources.indexOf(n.source),e+=o.encode(t-g),g=t,e+=o.encode(n.originalLine-1-l),l=n.originalLine-1,e+=o.encode(n.originalColumn-u),u=n.originalColumn,null!=n.name&&(r=this._names.indexOf(n.name),e+=o.encode(r-c),c=r)),p+=e}return p},t.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var r=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},t.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},t.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=t},function(e,n,r){function t(e){return e<0?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),r=e>>1;return n?-r:r}var i=r(3),s=5,a=1<>>=s,o>0&&(n|=l),r+=i.encode(n);while(o>0);return r},n.decode=function(e,n,r){var t,a,c=e.length,g=0,p=0;do{if(n>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(a=i.decode(e.charCodeAt(n++)),a===-1)throw new Error("Invalid base64 digit: "+e.charAt(n-1));t=!!(a&l),a&=u,g+=a<=0;c--)s=u[c],"."===s?u.splice(c,1):".."===s?l++:l>0&&(""===s?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=a?"/":"."),i?(i.path=r,o(i)):r}function s(e,n){""===e&&(e="."),""===n&&(n=".");var r=t(n),s=t(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),o(r);if(r||n.match(y))return n;if(s&&!s.host&&!s.path)return s.host=n,o(s);var a="/"===n.charAt(0)?n:i(e.replace(/\/+$/,"")+"/"+n);return s?(s.path=a,o(s)):a}function a(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==n.indexOf(e+"/");){var t=e.lastIndexOf("/");if(t<0)return n;if(e=e.slice(0,t),e.match(/^([^\/]+:\/)?\/*$/))return n;++r}return Array(r+1).join("../")+n.substr(e.length+1)}function u(e){return e}function l(e){return g(e)?"$"+e:e}function c(e){return g(e)?e.slice(1):e}function g(e){if(!e)return!1;var n=e.length;if(n<9)return!1;if(95!==e.charCodeAt(n-1)||95!==e.charCodeAt(n-2)||111!==e.charCodeAt(n-3)||116!==e.charCodeAt(n-4)||111!==e.charCodeAt(n-5)||114!==e.charCodeAt(n-6)||112!==e.charCodeAt(n-7)||95!==e.charCodeAt(n-8)||95!==e.charCodeAt(n-9))return!1;for(var r=n-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,n,r){var t=f(e.source,n.source);return 0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t||r?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=e.generatedLine-n.generatedLine,0!==t?t:f(e.name,n.name)))))}function h(e,n,r){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t||r?t:(t=f(e.source,n.source),0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:f(e.name,n.name)))))}function f(e,n){return e===n?0:null===e?1:null===n?-1:e>n?1:-1}function d(e,n){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=f(e.source,n.source),0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:f(e.name,n.name)))))}function m(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}function _(e,n,r){if(n=n||"",e&&("/"!==e[e.length-1]&&"/"!==n[0]&&(e+="/"),n=e+n),r){var a=t(r);if(!a)throw new Error("sourceMapURL could not be parsed");if(a.path){var u=a.path.lastIndexOf("/");u>=0&&(a.path=a.path.substring(0,u+1))}n=s(o(a),n)}return i(n)}n.getArg=r;var v=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,y=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=o,n.normalize=i,n.join=s,n.isAbsolute=function(e){return"/"===e.charAt(0)||v.test(e)},n.relative=a;var C=function(){var e=Object.create(null);return!("__proto__"in e)}();n.toSetString=C?u:l,n.fromSetString=C?u:c,n.compareByOriginalPositions=p,n.compareByGeneratedPositionsDeflated=h,n.compareByGeneratedPositionsInflated=d,n.parseSourceMapInput=m,n.computeSourceURL=_},function(e,n,r){function t(){this._array=[],this._set=s?new Map:Object.create(null)}var o=r(4),i=Object.prototype.hasOwnProperty,s="undefined"!=typeof Map;t.fromArray=function(e,n){for(var r=new t,o=0,i=e.length;o=0)return n}else{var r=o.toSetString(e);if(i.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},t.prototype.at=function(e){if(e>=0&&er||t==r&&s>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=r(4);o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){t(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=o},function(e,n,r){function t(e,n){var r=e;return"string"==typeof e&&(r=a.parseSourceMapInput(e)),null!=r.sections?new s(r,n):new o(r,n)}function o(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var t=a.getArg(r,"version"),o=a.getArg(r,"sources"),i=a.getArg(r,"names",[]),s=a.getArg(r,"sourceRoot",null),u=a.getArg(r,"sourcesContent",null),c=a.getArg(r,"mappings"),g=a.getArg(r,"file",null);if(t!=this._version)throw new Error("Unsupported version: "+t);s&&(s=a.normalize(s)),o=o.map(String).map(a.normalize).map(function(e){return s&&a.isAbsolute(s)&&a.isAbsolute(e)?a.relative(s,e):e}),this._names=l.fromArray(i.map(String),!0),this._sources=l.fromArray(o,!0),this._absoluteSources=this._sources.toArray().map(function(e){return a.computeSourceURL(s,e,n)}),this.sourceRoot=s,this.sourcesContent=u,this._mappings=c,this._sourceMapURL=n,this.file=g}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function s(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var o=a.getArg(r,"version"),i=a.getArg(r,"sections");if(o!=this._version)throw new Error("Unsupported version: "+o);this._sources=new l,this._names=new l;var s={line:-1,column:0};this._sections=i.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var r=a.getArg(e,"offset"),o=a.getArg(r,"line"),i=a.getArg(r,"column");if(o=0){var i=this._originalMappings[o];if(void 0===e.column)for(var s=i.originalLine;i&&i.originalLine===s;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var l=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==l;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return t},n.SourceMapConsumer=t,o.prototype=Object.create(t.prototype),o.prototype.consumer=t,o.prototype._findSourceIndex=function(e){var n=e;if(null!=this.sourceRoot&&(n=a.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);var r;for(r=0;r1&&(r.source=d+o[1],d+=o[1],r.originalLine=h+o[2],h=r.originalLine,r.originalLine+=1,r.originalColumn=f+o[3],f=r.originalColumn,o.length>4&&(r.name=m+o[4],m+=o[4])),A.push(r),"number"==typeof r.originalLine&&S.push(r)}g(A,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=A,g(S,a.compareByOriginalPositions),this.__originalMappings=S},o.prototype._findMapping=function(e,n,r,t,o,i){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return u.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[r];if(o.generatedLine===n.generatedLine){var i=a.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),i=a.computeSourceURL(this.sourceRoot,i,this._sourceMapURL));var s=a.getArg(o,"name",null);return null!==s&&(s=this._names.at(s)),{source:i,line:a.getArg(o,"originalLine",null),column:a.getArg(o,"originalColumn",null),name:s}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;var r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];var t=e;null!=this.sourceRoot&&(t=a.relative(this.sourceRoot,t));var o;if(null!=this.sourceRoot&&(o=a.urlParse(this.sourceRoot))){var i=t.replace(/^file:\/\//,"");if("file"==o.scheme&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!o.path||"/"==o.path)&&this._sources.has("/"+t))return this.sourcesContent[this._sources.indexOf("/"+t)]}if(n)return null;throw new Error('"'+t+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=a.getArg(e,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};var r={source:n,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},o=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",t.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===r.source)return{line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=o,s.prototype=Object.create(t.prototype),s.prototype.constructor=t,s.prototype._version=3,Object.defineProperty(s.prototype,"sources",{get:function(){for(var e=[],n=0;n0?t-u>1?r(u,t,o,i,s,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,o,i,s,a):a==n.LEAST_UPPER_BOUND?u:e<0?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,o,i){if(0===t.length)return-1;var s=r(-1,t.length,e,t,o,i||n.GREATEST_LOWER_BOUND);if(s<0)return-1;for(;s-1>=0&&0===o(t[s],t[s-1],!0);)--s;return s}},function(e,n){function r(e,n,r){var t=e[n];e[n]=e[r],e[r]=t}function t(e,n){return Math.round(e+Math.random()*(n-e))}function o(e,n,i,s){if(i=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},t.prototype.walk=function(e){for(var n,r=0,t=this.children.length;r0){for(n=[],r=0;r 0 && aGenerated.column >= 0\n\t && !aOriginal && !aSource && !aName) {\n\t // Case 1.\n\t return;\n\t }\n\t else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n\t && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n\t && aGenerated.line > 0 && aGenerated.column >= 0\n\t && aOriginal.line > 0 && aOriginal.column >= 0\n\t && aSource) {\n\t // Cases 2 and 3.\n\t return;\n\t }\n\t else {\n\t throw new Error('Invalid mapping: ' + JSON.stringify({\n\t generated: aGenerated,\n\t source: aSource,\n\t original: aOriginal,\n\t name: aName\n\t }));\n\t }\n\t };\n\t\n\t/**\n\t * Serialize the accumulated mappings in to the stream of base 64 VLQs\n\t * specified by the source map format.\n\t */\n\tSourceMapGenerator.prototype._serializeMappings =\n\t function SourceMapGenerator_serializeMappings() {\n\t var previousGeneratedColumn = 0;\n\t var previousGeneratedLine = 1;\n\t var previousOriginalColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousName = 0;\n\t var previousSource = 0;\n\t var result = '';\n\t var next;\n\t var mapping;\n\t var nameIdx;\n\t var sourceIdx;\n\t\n\t var mappings = this._mappings.toArray();\n\t for (var i = 0, len = mappings.length; i < len; i++) {\n\t mapping = mappings[i];\n\t next = ''\n\t\n\t if (mapping.generatedLine !== previousGeneratedLine) {\n\t previousGeneratedColumn = 0;\n\t while (mapping.generatedLine !== previousGeneratedLine) {\n\t next += ';';\n\t previousGeneratedLine++;\n\t }\n\t }\n\t else {\n\t if (i > 0) {\n\t if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n\t continue;\n\t }\n\t next += ',';\n\t }\n\t }\n\t\n\t next += base64VLQ.encode(mapping.generatedColumn\n\t - previousGeneratedColumn);\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (mapping.source != null) {\n\t sourceIdx = this._sources.indexOf(mapping.source);\n\t next += base64VLQ.encode(sourceIdx - previousSource);\n\t previousSource = sourceIdx;\n\t\n\t // lines are stored 0-based in SourceMap spec version 3\n\t next += base64VLQ.encode(mapping.originalLine - 1\n\t - previousOriginalLine);\n\t previousOriginalLine = mapping.originalLine - 1;\n\t\n\t next += base64VLQ.encode(mapping.originalColumn\n\t - previousOriginalColumn);\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (mapping.name != null) {\n\t nameIdx = this._names.indexOf(mapping.name);\n\t next += base64VLQ.encode(nameIdx - previousName);\n\t previousName = nameIdx;\n\t }\n\t }\n\t\n\t result += next;\n\t }\n\t\n\t return result;\n\t };\n\t\n\tSourceMapGenerator.prototype._generateSourcesContent =\n\t function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n\t return aSources.map(function (source) {\n\t if (!this._sourcesContents) {\n\t return null;\n\t }\n\t if (aSourceRoot != null) {\n\t source = util.relative(aSourceRoot, source);\n\t }\n\t var key = util.toSetString(source);\n\t return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n\t ? this._sourcesContents[key]\n\t : null;\n\t }, this);\n\t };\n\t\n\t/**\n\t * Externalize the source map.\n\t */\n\tSourceMapGenerator.prototype.toJSON =\n\t function SourceMapGenerator_toJSON() {\n\t var map = {\n\t version: this._version,\n\t sources: this._sources.toArray(),\n\t names: this._names.toArray(),\n\t mappings: this._serializeMappings()\n\t };\n\t if (this._file != null) {\n\t map.file = this._file;\n\t }\n\t if (this._sourceRoot != null) {\n\t map.sourceRoot = this._sourceRoot;\n\t }\n\t if (this._sourcesContents) {\n\t map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n\t }\n\t\n\t return map;\n\t };\n\t\n\t/**\n\t * Render the source map being generated to a string.\n\t */\n\tSourceMapGenerator.prototype.toString =\n\t function SourceMapGenerator_toString() {\n\t return JSON.stringify(this.toJSON());\n\t };\n\t\n\texports.SourceMapGenerator = SourceMapGenerator;\n\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t *\n\t * Based on the Base 64 VLQ implementation in Closure Compiler:\n\t * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n\t *\n\t * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n\t * Redistribution and use in source and binary forms, with or without\n\t * modification, are permitted provided that the following conditions are\n\t * met:\n\t *\n\t * * Redistributions of source code must retain the above copyright\n\t * notice, this list of conditions and the following disclaimer.\n\t * * Redistributions in binary form must reproduce the above\n\t * copyright notice, this list of conditions and the following\n\t * disclaimer in the documentation and/or other materials provided\n\t * with the distribution.\n\t * * Neither the name of Google Inc. nor the names of its\n\t * contributors may be used to endorse or promote products derived\n\t * from this software without specific prior written permission.\n\t *\n\t * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\t * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\t * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\t * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\t * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\t * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\t * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\t * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\t * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\t * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\t */\n\t\n\tvar base64 = __webpack_require__(3);\n\t\n\t// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n\t// length quantities we use in the source map spec, the first bit is the sign,\n\t// the next four bits are the actual value, and the 6th bit is the\n\t// continuation bit. The continuation bit tells us whether there are more\n\t// digits in this value following this digit.\n\t//\n\t// Continuation\n\t// | Sign\n\t// | |\n\t// V V\n\t// 101011\n\t\n\tvar VLQ_BASE_SHIFT = 5;\n\t\n\t// binary: 100000\n\tvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\t\n\t// binary: 011111\n\tvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\t\n\t// binary: 100000\n\tvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\t\n\t/**\n\t * Converts from a two-complement value to a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n\t * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n\t */\n\tfunction toVLQSigned(aValue) {\n\t return aValue < 0\n\t ? ((-aValue) << 1) + 1\n\t : (aValue << 1) + 0;\n\t}\n\t\n\t/**\n\t * Converts to a two-complement value from a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n\t * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n\t */\n\tfunction fromVLQSigned(aValue) {\n\t var isNegative = (aValue & 1) === 1;\n\t var shifted = aValue >> 1;\n\t return isNegative\n\t ? -shifted\n\t : shifted;\n\t}\n\t\n\t/**\n\t * Returns the base 64 VLQ encoded value.\n\t */\n\texports.encode = function base64VLQ_encode(aValue) {\n\t var encoded = \"\";\n\t var digit;\n\t\n\t var vlq = toVLQSigned(aValue);\n\t\n\t do {\n\t digit = vlq & VLQ_BASE_MASK;\n\t vlq >>>= VLQ_BASE_SHIFT;\n\t if (vlq > 0) {\n\t // There are still more digits in this value, so we must make sure the\n\t // continuation bit is marked.\n\t digit |= VLQ_CONTINUATION_BIT;\n\t }\n\t encoded += base64.encode(digit);\n\t } while (vlq > 0);\n\t\n\t return encoded;\n\t};\n\t\n\t/**\n\t * Decodes the next base 64 VLQ value from the given string and returns the\n\t * value and the rest of the string via the out parameter.\n\t */\n\texports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n\t var strLen = aStr.length;\n\t var result = 0;\n\t var shift = 0;\n\t var continuation, digit;\n\t\n\t do {\n\t if (aIndex >= strLen) {\n\t throw new Error(\"Expected more digits in base 64 VLQ value.\");\n\t }\n\t\n\t digit = base64.decode(aStr.charCodeAt(aIndex++));\n\t if (digit === -1) {\n\t throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n\t }\n\t\n\t continuation = !!(digit & VLQ_CONTINUATION_BIT);\n\t digit &= VLQ_BASE_MASK;\n\t result = result + (digit << shift);\n\t shift += VLQ_BASE_SHIFT;\n\t } while (continuation);\n\t\n\t aOutParam.value = fromVLQSigned(result);\n\t aOutParam.rest = aIndex;\n\t};\n\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\t\n\t/**\n\t * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n\t */\n\texports.encode = function (number) {\n\t if (0 <= number && number < intToCharMap.length) {\n\t return intToCharMap[number];\n\t }\n\t throw new TypeError(\"Must be between 0 and 63: \" + number);\n\t};\n\t\n\t/**\n\t * Decode a single base 64 character code digit to an integer. Returns -1 on\n\t * failure.\n\t */\n\texports.decode = function (charCode) {\n\t var bigA = 65; // 'A'\n\t var bigZ = 90; // 'Z'\n\t\n\t var littleA = 97; // 'a'\n\t var littleZ = 122; // 'z'\n\t\n\t var zero = 48; // '0'\n\t var nine = 57; // '9'\n\t\n\t var plus = 43; // '+'\n\t var slash = 47; // '/'\n\t\n\t var littleOffset = 26;\n\t var numberOffset = 52;\n\t\n\t // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t if (bigA <= charCode && charCode <= bigZ) {\n\t return (charCode - bigA);\n\t }\n\t\n\t // 26 - 51: abcdefghijklmnopqrstuvwxyz\n\t if (littleA <= charCode && charCode <= littleZ) {\n\t return (charCode - littleA + littleOffset);\n\t }\n\t\n\t // 52 - 61: 0123456789\n\t if (zero <= charCode && charCode <= nine) {\n\t return (charCode - zero + numberOffset);\n\t }\n\t\n\t // 62: +\n\t if (charCode == plus) {\n\t return 62;\n\t }\n\t\n\t // 63: /\n\t if (charCode == slash) {\n\t return 63;\n\t }\n\t\n\t // Invalid base64 digit.\n\t return -1;\n\t};\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t/**\n\t * This is a helper function for getting values from parameter/options\n\t * objects.\n\t *\n\t * @param args The object we are extracting values from\n\t * @param name The name of the property we are getting.\n\t * @param defaultValue An optional value to return if the property is missing\n\t * from the object. If this is not specified and the property is missing, an\n\t * error will be thrown.\n\t */\n\tfunction getArg(aArgs, aName, aDefaultValue) {\n\t if (aName in aArgs) {\n\t return aArgs[aName];\n\t } else if (arguments.length === 3) {\n\t return aDefaultValue;\n\t } else {\n\t throw new Error('\"' + aName + '\" is a required argument.');\n\t }\n\t}\n\texports.getArg = getArg;\n\t\n\tvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\n\tvar dataUrlRegexp = /^data:.+\\,.+$/;\n\t\n\tfunction urlParse(aUrl) {\n\t var match = aUrl.match(urlRegexp);\n\t if (!match) {\n\t return null;\n\t }\n\t return {\n\t scheme: match[1],\n\t auth: match[2],\n\t host: match[3],\n\t port: match[4],\n\t path: match[5]\n\t };\n\t}\n\texports.urlParse = urlParse;\n\t\n\tfunction urlGenerate(aParsedUrl) {\n\t var url = '';\n\t if (aParsedUrl.scheme) {\n\t url += aParsedUrl.scheme + ':';\n\t }\n\t url += '//';\n\t if (aParsedUrl.auth) {\n\t url += aParsedUrl.auth + '@';\n\t }\n\t if (aParsedUrl.host) {\n\t url += aParsedUrl.host;\n\t }\n\t if (aParsedUrl.port) {\n\t url += \":\" + aParsedUrl.port\n\t }\n\t if (aParsedUrl.path) {\n\t url += aParsedUrl.path;\n\t }\n\t return url;\n\t}\n\texports.urlGenerate = urlGenerate;\n\t\n\t/**\n\t * Normalizes a path, or the path portion of a URL:\n\t *\n\t * - Replaces consecutive slashes with one slash.\n\t * - Removes unnecessary '.' parts.\n\t * - Removes unnecessary '/..' parts.\n\t *\n\t * Based on code in the Node.js 'path' core module.\n\t *\n\t * @param aPath The path or url to normalize.\n\t */\n\tfunction normalize(aPath) {\n\t var path = aPath;\n\t var url = urlParse(aPath);\n\t if (url) {\n\t if (!url.path) {\n\t return aPath;\n\t }\n\t path = url.path;\n\t }\n\t var isAbsolute = exports.isAbsolute(path);\n\t\n\t var parts = path.split(/\\/+/);\n\t for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n\t part = parts[i];\n\t if (part === '.') {\n\t parts.splice(i, 1);\n\t } else if (part === '..') {\n\t up++;\n\t } else if (up > 0) {\n\t if (part === '') {\n\t // The first part is blank if the path is absolute. Trying to go\n\t // above the root is a no-op. Therefore we can remove all '..' parts\n\t // directly after the root.\n\t parts.splice(i + 1, up);\n\t up = 0;\n\t } else {\n\t parts.splice(i, 2);\n\t up--;\n\t }\n\t }\n\t }\n\t path = parts.join('/');\n\t\n\t if (path === '') {\n\t path = isAbsolute ? '/' : '.';\n\t }\n\t\n\t if (url) {\n\t url.path = path;\n\t return urlGenerate(url);\n\t }\n\t return path;\n\t}\n\texports.normalize = normalize;\n\t\n\t/**\n\t * Joins two paths/URLs.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be joined with the root.\n\t *\n\t * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n\t * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n\t * first.\n\t * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n\t * is updated with the result and aRoot is returned. Otherwise the result\n\t * is returned.\n\t * - If aPath is absolute, the result is aPath.\n\t * - Otherwise the two paths are joined with a slash.\n\t * - Joining for example 'http://' and 'www.example.com' is also supported.\n\t */\n\tfunction join(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t if (aPath === \"\") {\n\t aPath = \".\";\n\t }\n\t var aPathUrl = urlParse(aPath);\n\t var aRootUrl = urlParse(aRoot);\n\t if (aRootUrl) {\n\t aRoot = aRootUrl.path || '/';\n\t }\n\t\n\t // `join(foo, '//www.example.org')`\n\t if (aPathUrl && !aPathUrl.scheme) {\n\t if (aRootUrl) {\n\t aPathUrl.scheme = aRootUrl.scheme;\n\t }\n\t return urlGenerate(aPathUrl);\n\t }\n\t\n\t if (aPathUrl || aPath.match(dataUrlRegexp)) {\n\t return aPath;\n\t }\n\t\n\t // `join('http://', 'www.example.com')`\n\t if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n\t aRootUrl.host = aPath;\n\t return urlGenerate(aRootUrl);\n\t }\n\t\n\t var joined = aPath.charAt(0) === '/'\n\t ? aPath\n\t : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\t\n\t if (aRootUrl) {\n\t aRootUrl.path = joined;\n\t return urlGenerate(aRootUrl);\n\t }\n\t return joined;\n\t}\n\texports.join = join;\n\t\n\texports.isAbsolute = function (aPath) {\n\t return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n\t};\n\t\n\t/**\n\t * Make a path relative to a URL or another path.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be made relative to aRoot.\n\t */\n\tfunction relative(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t\n\t aRoot = aRoot.replace(/\\/$/, '');\n\t\n\t // It is possible for the path to be above the root. In this case, simply\n\t // checking whether the root is a prefix of the path won't work. Instead, we\n\t // need to remove components from the root one by one, until either we find\n\t // a prefix that fits, or we run out of components to remove.\n\t var level = 0;\n\t while (aPath.indexOf(aRoot + '/') !== 0) {\n\t var index = aRoot.lastIndexOf(\"/\");\n\t if (index < 0) {\n\t return aPath;\n\t }\n\t\n\t // If the only part of the root that is left is the scheme (i.e. http://,\n\t // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n\t // have exhausted all components, so the path is not relative to the root.\n\t aRoot = aRoot.slice(0, index);\n\t if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n\t return aPath;\n\t }\n\t\n\t ++level;\n\t }\n\t\n\t // Make sure we add a \"../\" for each component we removed from the root.\n\t return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n\t}\n\texports.relative = relative;\n\t\n\tvar supportsNullProto = (function () {\n\t var obj = Object.create(null);\n\t return !('__proto__' in obj);\n\t}());\n\t\n\tfunction identity (s) {\n\t return s;\n\t}\n\t\n\t/**\n\t * Because behavior goes wacky when you set `__proto__` on objects, we\n\t * have to prefix all the strings in our set with an arbitrary character.\n\t *\n\t * See https://github.com/mozilla/source-map/pull/31 and\n\t * https://github.com/mozilla/source-map/issues/30\n\t *\n\t * @param String aStr\n\t */\n\tfunction toSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return '$' + aStr;\n\t }\n\t\n\t return aStr;\n\t}\n\texports.toSetString = supportsNullProto ? identity : toSetString;\n\t\n\tfunction fromSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return aStr.slice(1);\n\t }\n\t\n\t return aStr;\n\t}\n\texports.fromSetString = supportsNullProto ? identity : fromSetString;\n\t\n\tfunction isProtoString(s) {\n\t if (!s) {\n\t return false;\n\t }\n\t\n\t var length = s.length;\n\t\n\t if (length < 9 /* \"__proto__\".length */) {\n\t return false;\n\t }\n\t\n\t if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n\t s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n\t s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n\t s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 9) !== 95 /* '_' */) {\n\t return false;\n\t }\n\t\n\t for (var i = length - 10; i >= 0; i--) {\n\t if (s.charCodeAt(i) !== 36 /* '$' */) {\n\t return false;\n\t }\n\t }\n\t\n\t return true;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings where the original positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same original source/line/column, but different generated\n\t * line and column the same. Useful when searching for a mapping with a\n\t * stubbed out mapping.\n\t */\n\tfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n\t var cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0 || onlyCompareOriginal) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByOriginalPositions = compareByOriginalPositions;\n\t\n\t/**\n\t * Comparator between two mappings with deflated source and name indices where\n\t * the generated positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same generated line and column, but different\n\t * source/name/original line and column the same. Useful when searching for a\n\t * mapping with a stubbed out mapping.\n\t */\n\tfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0 || onlyCompareGenerated) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\t\n\tfunction strcmp(aStr1, aStr2) {\n\t if (aStr1 === aStr2) {\n\t return 0;\n\t }\n\t\n\t if (aStr1 === null) {\n\t return 1; // aStr2 !== null\n\t }\n\t\n\t if (aStr2 === null) {\n\t return -1; // aStr1 !== null\n\t }\n\t\n\t if (aStr1 > aStr2) {\n\t return 1;\n\t }\n\t\n\t return -1;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings with inflated source and name strings where\n\t * the generated positions are compared.\n\t */\n\tfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\t\n\t/**\n\t * Strip any JSON XSSI avoidance prefix from the string (as documented\n\t * in the source maps specification), and then parse the string as\n\t * JSON.\n\t */\n\tfunction parseSourceMapInput(str) {\n\t return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n\t}\n\texports.parseSourceMapInput = parseSourceMapInput;\n\t\n\t/**\n\t * Compute the URL of a source given the the source root, the source's\n\t * URL, and the source map's URL.\n\t */\n\tfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n\t sourceURL = sourceURL || '';\n\t\n\t if (sourceRoot) {\n\t // This follows what Chrome does.\n\t if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n\t sourceRoot += '/';\n\t }\n\t // The spec says:\n\t // Line 4: An optional source root, useful for relocating source\n\t // files on a server or removing repeated values in the\n\t // “sources” entry. This value is prepended to the individual\n\t // entries in the “source” field.\n\t sourceURL = sourceRoot + sourceURL;\n\t }\n\t\n\t // Historically, SourceMapConsumer did not take the sourceMapURL as\n\t // a parameter. This mode is still somewhat supported, which is why\n\t // this code block is conditional. However, it's preferable to pass\n\t // the source map URL to SourceMapConsumer, so that this function\n\t // can implement the source URL resolution algorithm as outlined in\n\t // the spec. This block is basically the equivalent of:\n\t // new URL(sourceURL, sourceMapURL).toString()\n\t // ... except it avoids using URL, which wasn't available in the\n\t // older releases of node still supported by this library.\n\t //\n\t // The spec says:\n\t // If the sources are not absolute URLs after prepending of the\n\t // “sourceRoot”, the sources are resolved relative to the\n\t // SourceMap (like resolving script src in a html document).\n\t if (sourceMapURL) {\n\t var parsed = urlParse(sourceMapURL);\n\t if (!parsed) {\n\t throw new Error(\"sourceMapURL could not be parsed\");\n\t }\n\t if (parsed.path) {\n\t // Strip the last path component, but keep the \"/\".\n\t var index = parsed.path.lastIndexOf('/');\n\t if (index >= 0) {\n\t parsed.path = parsed.path.substring(0, index + 1);\n\t }\n\t }\n\t sourceURL = join(urlGenerate(parsed), sourceURL);\n\t }\n\t\n\t return normalize(sourceURL);\n\t}\n\texports.computeSourceURL = computeSourceURL;\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar has = Object.prototype.hasOwnProperty;\n\tvar hasNativeMap = typeof Map !== \"undefined\";\n\t\n\t/**\n\t * A data structure which is a combination of an array and a set. Adding a new\n\t * member is O(1), testing for membership is O(1), and finding the index of an\n\t * element is O(1). Removing elements from the set is not supported. Only\n\t * strings are supported for membership.\n\t */\n\tfunction ArraySet() {\n\t this._array = [];\n\t this._set = hasNativeMap ? new Map() : Object.create(null);\n\t}\n\t\n\t/**\n\t * Static method for creating ArraySet instances from an existing array.\n\t */\n\tArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n\t var set = new ArraySet();\n\t for (var i = 0, len = aArray.length; i < len; i++) {\n\t set.add(aArray[i], aAllowDuplicates);\n\t }\n\t return set;\n\t};\n\t\n\t/**\n\t * Return how many unique items are in this ArraySet. If duplicates have been\n\t * added, than those do not count towards the size.\n\t *\n\t * @returns Number\n\t */\n\tArraySet.prototype.size = function ArraySet_size() {\n\t return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n\t};\n\t\n\t/**\n\t * Add the given string to this set.\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n\t var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n\t var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n\t var idx = this._array.length;\n\t if (!isDuplicate || aAllowDuplicates) {\n\t this._array.push(aStr);\n\t }\n\t if (!isDuplicate) {\n\t if (hasNativeMap) {\n\t this._set.set(aStr, idx);\n\t } else {\n\t this._set[sStr] = idx;\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Is the given string a member of this set?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.has = function ArraySet_has(aStr) {\n\t if (hasNativeMap) {\n\t return this._set.has(aStr);\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t return has.call(this._set, sStr);\n\t }\n\t};\n\t\n\t/**\n\t * What is the index of the given string in the array?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n\t if (hasNativeMap) {\n\t var idx = this._set.get(aStr);\n\t if (idx >= 0) {\n\t return idx;\n\t }\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t if (has.call(this._set, sStr)) {\n\t return this._set[sStr];\n\t }\n\t }\n\t\n\t throw new Error('\"' + aStr + '\" is not in the set.');\n\t};\n\t\n\t/**\n\t * What is the element at the given index?\n\t *\n\t * @param Number aIdx\n\t */\n\tArraySet.prototype.at = function ArraySet_at(aIdx) {\n\t if (aIdx >= 0 && aIdx < this._array.length) {\n\t return this._array[aIdx];\n\t }\n\t throw new Error('No element indexed by ' + aIdx);\n\t};\n\t\n\t/**\n\t * Returns the array representation of this set (which has the proper indices\n\t * indicated by indexOf). Note that this is a copy of the internal array used\n\t * for storing the members so that no one can mess with internal state.\n\t */\n\tArraySet.prototype.toArray = function ArraySet_toArray() {\n\t return this._array.slice();\n\t};\n\t\n\texports.ArraySet = ArraySet;\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2014 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\t\n\t/**\n\t * Determine whether mappingB is after mappingA with respect to generated\n\t * position.\n\t */\n\tfunction generatedPositionAfter(mappingA, mappingB) {\n\t // Optimized for most common case\n\t var lineA = mappingA.generatedLine;\n\t var lineB = mappingB.generatedLine;\n\t var columnA = mappingA.generatedColumn;\n\t var columnB = mappingB.generatedColumn;\n\t return lineB > lineA || lineB == lineA && columnB >= columnA ||\n\t util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n\t}\n\t\n\t/**\n\t * A data structure to provide a sorted view of accumulated mappings in a\n\t * performance conscious manner. It trades a neglibable overhead in general\n\t * case for a large speedup in case of mappings being added in order.\n\t */\n\tfunction MappingList() {\n\t this._array = [];\n\t this._sorted = true;\n\t // Serves as infimum\n\t this._last = {generatedLine: -1, generatedColumn: 0};\n\t}\n\t\n\t/**\n\t * Iterate through internal items. This method takes the same arguments that\n\t * `Array.prototype.forEach` takes.\n\t *\n\t * NOTE: The order of the mappings is NOT guaranteed.\n\t */\n\tMappingList.prototype.unsortedForEach =\n\t function MappingList_forEach(aCallback, aThisArg) {\n\t this._array.forEach(aCallback, aThisArg);\n\t };\n\t\n\t/**\n\t * Add the given source mapping.\n\t *\n\t * @param Object aMapping\n\t */\n\tMappingList.prototype.add = function MappingList_add(aMapping) {\n\t if (generatedPositionAfter(this._last, aMapping)) {\n\t this._last = aMapping;\n\t this._array.push(aMapping);\n\t } else {\n\t this._sorted = false;\n\t this._array.push(aMapping);\n\t }\n\t};\n\t\n\t/**\n\t * Returns the flat, sorted array of mappings. The mappings are sorted by\n\t * generated position.\n\t *\n\t * WARNING: This method returns internal data without copying, for\n\t * performance. The return value must NOT be mutated, and should be treated as\n\t * an immutable borrow. If you want to take ownership, you must make your own\n\t * copy.\n\t */\n\tMappingList.prototype.toArray = function MappingList_toArray() {\n\t if (!this._sorted) {\n\t this._array.sort(util.compareByGeneratedPositionsInflated);\n\t this._sorted = true;\n\t }\n\t return this._array;\n\t};\n\t\n\texports.MappingList = MappingList;\n\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar binarySearch = __webpack_require__(8);\n\tvar ArraySet = __webpack_require__(5).ArraySet;\n\tvar base64VLQ = __webpack_require__(2);\n\tvar quickSort = __webpack_require__(9).quickSort;\n\t\n\tfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t return sourceMap.sections != null\n\t ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n\t : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n\t}\n\t\n\tSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n\t return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n\t}\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tSourceMapConsumer.prototype._version = 3;\n\t\n\t// `__generatedMappings` and `__originalMappings` are arrays that hold the\n\t// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n\t// are lazily instantiated, accessed via the `_generatedMappings` and\n\t// `_originalMappings` getters respectively, and we only parse the mappings\n\t// and create these arrays once queried for a source location. We jump through\n\t// these hoops because there can be many thousands of mappings, and parsing\n\t// them is expensive, so we only want to do it if we must.\n\t//\n\t// Each object in the arrays is of the form:\n\t//\n\t// {\n\t// generatedLine: The line number in the generated code,\n\t// generatedColumn: The column number in the generated code,\n\t// source: The path to the original source file that generated this\n\t// chunk of code,\n\t// originalLine: The line number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// originalColumn: The column number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// name: The name of the original symbol which generated this chunk of\n\t// code.\n\t// }\n\t//\n\t// All properties except for `generatedLine` and `generatedColumn` can be\n\t// `null`.\n\t//\n\t// `_generatedMappings` is ordered by the generated positions.\n\t//\n\t// `_originalMappings` is ordered by the original positions.\n\t\n\tSourceMapConsumer.prototype.__generatedMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__generatedMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__generatedMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype.__originalMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__originalMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__originalMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype._charIsMappingSeparator =\n\t function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n\t var c = aStr.charAt(index);\n\t return c === \";\" || c === \",\";\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t throw new Error(\"Subclasses must implement _parseMappings\");\n\t };\n\t\n\tSourceMapConsumer.GENERATED_ORDER = 1;\n\tSourceMapConsumer.ORIGINAL_ORDER = 2;\n\t\n\tSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\n\tSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Iterate over each mapping between an original source/line/column and a\n\t * generated line/column in this source map.\n\t *\n\t * @param Function aCallback\n\t * The function that is called with each mapping.\n\t * @param Object aContext\n\t * Optional. If specified, this object will be the value of `this` every\n\t * time that `aCallback` is called.\n\t * @param aOrder\n\t * Either `SourceMapConsumer.GENERATED_ORDER` or\n\t * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n\t * iterate over the mappings sorted by the generated file's line/column\n\t * order or the original's source/line/column order, respectively. Defaults to\n\t * `SourceMapConsumer.GENERATED_ORDER`.\n\t */\n\tSourceMapConsumer.prototype.eachMapping =\n\t function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n\t var context = aContext || null;\n\t var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\t\n\t var mappings;\n\t switch (order) {\n\t case SourceMapConsumer.GENERATED_ORDER:\n\t mappings = this._generatedMappings;\n\t break;\n\t case SourceMapConsumer.ORIGINAL_ORDER:\n\t mappings = this._originalMappings;\n\t break;\n\t default:\n\t throw new Error(\"Unknown order of iteration.\");\n\t }\n\t\n\t var sourceRoot = this.sourceRoot;\n\t mappings.map(function (mapping) {\n\t var source = mapping.source === null ? null : this._sources.at(mapping.source);\n\t source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n\t return {\n\t source: source,\n\t generatedLine: mapping.generatedLine,\n\t generatedColumn: mapping.generatedColumn,\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: mapping.name === null ? null : this._names.at(mapping.name)\n\t };\n\t }, this).forEach(aCallback, context);\n\t };\n\t\n\t/**\n\t * Returns all generated line and column information for the original source,\n\t * line, and column provided. If no column is provided, returns all mappings\n\t * corresponding to a either the line we are searching for or the next\n\t * closest line that has any mappings. Otherwise, returns all mappings\n\t * corresponding to the given line and either the column we are searching for\n\t * or the next closest column that has any offsets.\n\t *\n\t * The only argument is an object with the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number is 1-based.\n\t * - column: Optional. the column number in the original source.\n\t * The column number is 0-based.\n\t *\n\t * and an array of objects is returned, each with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tSourceMapConsumer.prototype.allGeneratedPositionsFor =\n\t function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n\t var line = util.getArg(aArgs, 'line');\n\t\n\t // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n\t // returns the index of the closest mapping less than the needle. By\n\t // setting needle.originalColumn to 0, we thus find the last mapping for\n\t // the given line, provided such a mapping exists.\n\t var needle = {\n\t source: util.getArg(aArgs, 'source'),\n\t originalLine: line,\n\t originalColumn: util.getArg(aArgs, 'column', 0)\n\t };\n\t\n\t needle.source = this._findSourceIndex(needle.source);\n\t if (needle.source < 0) {\n\t return [];\n\t }\n\t\n\t var mappings = [];\n\t\n\t var index = this._findMapping(needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t binarySearch.LEAST_UPPER_BOUND);\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (aArgs.column === undefined) {\n\t var originalLine = mapping.originalLine;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we found. Since\n\t // mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we found.\n\t while (mapping && mapping.originalLine === originalLine) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t } else {\n\t var originalColumn = mapping.originalColumn;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we were searching for.\n\t // Since mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we are searching for.\n\t while (mapping &&\n\t mapping.originalLine === line &&\n\t mapping.originalColumn == originalColumn) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t }\n\t }\n\t\n\t return mappings;\n\t };\n\t\n\texports.SourceMapConsumer = SourceMapConsumer;\n\t\n\t/**\n\t * A BasicSourceMapConsumer instance represents a parsed source map which we can\n\t * query for information about the original file positions by giving it a file\n\t * position in the generated source.\n\t *\n\t * The first parameter is the raw source map (either as a JSON string, or\n\t * already parsed to an object). According to the spec, source maps have the\n\t * following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - sources: An array of URLs to the original source files.\n\t * - names: An array of identifiers which can be referrenced by individual mappings.\n\t * - sourceRoot: Optional. The URL root from which all sources are relative.\n\t * - sourcesContent: Optional. An array of contents of the original source files.\n\t * - mappings: A string of base64 VLQs which contain the actual mappings.\n\t * - file: Optional. The generated file this source map is associated with.\n\t *\n\t * Here is an example source map, taken from the source map spec[0]:\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"out.js\",\n\t * sourceRoot : \"\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AA,AB;;ABCDE;\"\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n\t */\n\tfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sources = util.getArg(sourceMap, 'sources');\n\t // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n\t // requires the array) to play nice here.\n\t var names = util.getArg(sourceMap, 'names', []);\n\t var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n\t var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n\t var mappings = util.getArg(sourceMap, 'mappings');\n\t var file = util.getArg(sourceMap, 'file', null);\n\t\n\t // Once again, Sass deviates from the spec and supplies the version as a\n\t // string rather than a number, so we use loose equality checking here.\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t if (sourceRoot) {\n\t sourceRoot = util.normalize(sourceRoot);\n\t }\n\t\n\t sources = sources\n\t .map(String)\n\t // Some source maps produce relative source paths like \"./foo.js\" instead of\n\t // \"foo.js\". Normalize these first so that future comparisons will succeed.\n\t // See bugzil.la/1090768.\n\t .map(util.normalize)\n\t // Always ensure that absolute sources are internally stored relative to\n\t // the source root, if the source root is absolute. Not doing this would\n\t // be particularly problematic when the source root is a prefix of the\n\t // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n\t .map(function (source) {\n\t return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n\t ? util.relative(sourceRoot, source)\n\t : source;\n\t });\n\t\n\t // Pass `true` below to allow duplicate names and sources. While source maps\n\t // are intended to be compressed and deduplicated, the TypeScript compiler\n\t // sometimes generates source maps with duplicates in them. See Github issue\n\t // #72 and bugzil.la/889492.\n\t this._names = ArraySet.fromArray(names.map(String), true);\n\t this._sources = ArraySet.fromArray(sources, true);\n\t\n\t this._absoluteSources = this._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t this.sourceRoot = sourceRoot;\n\t this.sourcesContent = sourcesContent;\n\t this._mappings = mappings;\n\t this._sourceMapURL = aSourceMapURL;\n\t this.file = file;\n\t}\n\t\n\tBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\t\n\t/**\n\t * Utility function to find the index of a source. Returns -1 if not\n\t * found.\n\t */\n\tBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t if (this._sources.has(relativeSource)) {\n\t return this._sources.indexOf(relativeSource);\n\t }\n\t\n\t // Maybe aSource is an absolute URL as returned by |sources|. In\n\t // this case we can't simply undo the transform.\n\t var i;\n\t for (i = 0; i < this._absoluteSources.length; ++i) {\n\t if (this._absoluteSources[i] == aSource) {\n\t return i;\n\t }\n\t }\n\t\n\t return -1;\n\t};\n\t\n\t/**\n\t * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n\t *\n\t * @param SourceMapGenerator aSourceMap\n\t * The source map that will be consumed.\n\t * @param String aSourceMapURL\n\t * The URL at which the source map can be found (optional)\n\t * @returns BasicSourceMapConsumer\n\t */\n\tBasicSourceMapConsumer.fromSourceMap =\n\t function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n\t var smc = Object.create(BasicSourceMapConsumer.prototype);\n\t\n\t var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n\t var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n\t smc.sourceRoot = aSourceMap._sourceRoot;\n\t smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n\t smc.sourceRoot);\n\t smc.file = aSourceMap._file;\n\t smc._sourceMapURL = aSourceMapURL;\n\t smc._absoluteSources = smc._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t // Because we are modifying the entries (by converting string sources and\n\t // names to indices into the sources and names ArraySets), we have to make\n\t // a copy of the entry or else bad things happen. Shared mutable state\n\t // strikes again! See github issue #191.\n\t\n\t var generatedMappings = aSourceMap._mappings.toArray().slice();\n\t var destGeneratedMappings = smc.__generatedMappings = [];\n\t var destOriginalMappings = smc.__originalMappings = [];\n\t\n\t for (var i = 0, length = generatedMappings.length; i < length; i++) {\n\t var srcMapping = generatedMappings[i];\n\t var destMapping = new Mapping;\n\t destMapping.generatedLine = srcMapping.generatedLine;\n\t destMapping.generatedColumn = srcMapping.generatedColumn;\n\t\n\t if (srcMapping.source) {\n\t destMapping.source = sources.indexOf(srcMapping.source);\n\t destMapping.originalLine = srcMapping.originalLine;\n\t destMapping.originalColumn = srcMapping.originalColumn;\n\t\n\t if (srcMapping.name) {\n\t destMapping.name = names.indexOf(srcMapping.name);\n\t }\n\t\n\t destOriginalMappings.push(destMapping);\n\t }\n\t\n\t destGeneratedMappings.push(destMapping);\n\t }\n\t\n\t quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\t\n\t return smc;\n\t };\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tBasicSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t return this._absoluteSources.slice();\n\t }\n\t});\n\t\n\t/**\n\t * Provide the JIT with a nice shape / hidden class.\n\t */\n\tfunction Mapping() {\n\t this.generatedLine = 0;\n\t this.generatedColumn = 0;\n\t this.source = null;\n\t this.originalLine = null;\n\t this.originalColumn = null;\n\t this.name = null;\n\t}\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tBasicSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t var generatedLine = 1;\n\t var previousGeneratedColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousOriginalColumn = 0;\n\t var previousSource = 0;\n\t var previousName = 0;\n\t var length = aStr.length;\n\t var index = 0;\n\t var cachedSegments = {};\n\t var temp = {};\n\t var originalMappings = [];\n\t var generatedMappings = [];\n\t var mapping, str, segment, end, value;\n\t\n\t while (index < length) {\n\t if (aStr.charAt(index) === ';') {\n\t generatedLine++;\n\t index++;\n\t previousGeneratedColumn = 0;\n\t }\n\t else if (aStr.charAt(index) === ',') {\n\t index++;\n\t }\n\t else {\n\t mapping = new Mapping();\n\t mapping.generatedLine = generatedLine;\n\t\n\t // Because each offset is encoded relative to the previous one,\n\t // many segments often have the same encoding. We can exploit this\n\t // fact by caching the parsed variable length fields of each segment,\n\t // allowing us to avoid a second parse if we encounter the same\n\t // segment again.\n\t for (end = index; end < length; end++) {\n\t if (this._charIsMappingSeparator(aStr, end)) {\n\t break;\n\t }\n\t }\n\t str = aStr.slice(index, end);\n\t\n\t segment = cachedSegments[str];\n\t if (segment) {\n\t index += str.length;\n\t } else {\n\t segment = [];\n\t while (index < end) {\n\t base64VLQ.decode(aStr, index, temp);\n\t value = temp.value;\n\t index = temp.rest;\n\t segment.push(value);\n\t }\n\t\n\t if (segment.length === 2) {\n\t throw new Error('Found a source, but no line and column');\n\t }\n\t\n\t if (segment.length === 3) {\n\t throw new Error('Found a source and line, but no column');\n\t }\n\t\n\t cachedSegments[str] = segment;\n\t }\n\t\n\t // Generated column.\n\t mapping.generatedColumn = previousGeneratedColumn + segment[0];\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (segment.length > 1) {\n\t // Original source.\n\t mapping.source = previousSource + segment[1];\n\t previousSource += segment[1];\n\t\n\t // Original line.\n\t mapping.originalLine = previousOriginalLine + segment[2];\n\t previousOriginalLine = mapping.originalLine;\n\t // Lines are stored 0-based\n\t mapping.originalLine += 1;\n\t\n\t // Original column.\n\t mapping.originalColumn = previousOriginalColumn + segment[3];\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (segment.length > 4) {\n\t // Original name.\n\t mapping.name = previousName + segment[4];\n\t previousName += segment[4];\n\t }\n\t }\n\t\n\t generatedMappings.push(mapping);\n\t if (typeof mapping.originalLine === 'number') {\n\t originalMappings.push(mapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t this.__generatedMappings = generatedMappings;\n\t\n\t quickSort(originalMappings, util.compareByOriginalPositions);\n\t this.__originalMappings = originalMappings;\n\t };\n\t\n\t/**\n\t * Find the mapping that best matches the hypothetical \"needle\" mapping that\n\t * we are searching for in the given \"haystack\" of mappings.\n\t */\n\tBasicSourceMapConsumer.prototype._findMapping =\n\t function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n\t aColumnName, aComparator, aBias) {\n\t // To return the position we are searching for, we must first find the\n\t // mapping for the given position and then return the opposite position it\n\t // points to. Because the mappings are sorted, we can use binary search to\n\t // find the best mapping.\n\t\n\t if (aNeedle[aLineName] <= 0) {\n\t throw new TypeError('Line must be greater than or equal to 1, got '\n\t + aNeedle[aLineName]);\n\t }\n\t if (aNeedle[aColumnName] < 0) {\n\t throw new TypeError('Column must be greater than or equal to 0, got '\n\t + aNeedle[aColumnName]);\n\t }\n\t\n\t return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n\t };\n\t\n\t/**\n\t * Compute the last column for each generated mapping. The last column is\n\t * inclusive.\n\t */\n\tBasicSourceMapConsumer.prototype.computeColumnSpans =\n\t function SourceMapConsumer_computeColumnSpans() {\n\t for (var index = 0; index < this._generatedMappings.length; ++index) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t // Mappings do not contain a field for the last generated columnt. We\n\t // can come up with an optimistic estimate, however, by assuming that\n\t // mappings are contiguous (i.e. given two consecutive mappings, the\n\t // first mapping ends where the second one starts).\n\t if (index + 1 < this._generatedMappings.length) {\n\t var nextMapping = this._generatedMappings[index + 1];\n\t\n\t if (mapping.generatedLine === nextMapping.generatedLine) {\n\t mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n\t continue;\n\t }\n\t }\n\t\n\t // The last mapping for each line spans the entire line.\n\t mapping.lastGeneratedColumn = Infinity;\n\t }\n\t };\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tBasicSourceMapConsumer.prototype.originalPositionFor =\n\t function SourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._generatedMappings,\n\t \"generatedLine\",\n\t \"generatedColumn\",\n\t util.compareByGeneratedPositionsDeflated,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t if (mapping.generatedLine === needle.generatedLine) {\n\t var source = util.getArg(mapping, 'source', null);\n\t if (source !== null) {\n\t source = this._sources.at(source);\n\t source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n\t }\n\t var name = util.getArg(mapping, 'name', null);\n\t if (name !== null) {\n\t name = this._names.at(name);\n\t }\n\t return {\n\t source: source,\n\t line: util.getArg(mapping, 'originalLine', null),\n\t column: util.getArg(mapping, 'originalColumn', null),\n\t name: name\n\t };\n\t }\n\t }\n\t\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function BasicSourceMapConsumer_hasContentsOfAllSources() {\n\t if (!this.sourcesContent) {\n\t return false;\n\t }\n\t return this.sourcesContent.length >= this._sources.size() &&\n\t !this.sourcesContent.some(function (sc) { return sc == null; });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tBasicSourceMapConsumer.prototype.sourceContentFor =\n\t function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t if (!this.sourcesContent) {\n\t return null;\n\t }\n\t\n\t var index = this._findSourceIndex(aSource);\n\t if (index >= 0) {\n\t return this.sourcesContent[index];\n\t }\n\t\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t var url;\n\t if (this.sourceRoot != null\n\t && (url = util.urlParse(this.sourceRoot))) {\n\t // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n\t // many users. We can help them out when they expect file:// URIs to\n\t // behave like it would if they were running a local HTTP server. See\n\t // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n\t var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n\t if (url.scheme == \"file\"\n\t && this._sources.has(fileUriAbsPath)) {\n\t return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n\t }\n\t\n\t if ((!url.path || url.path == \"/\")\n\t && this._sources.has(\"/\" + relativeSource)) {\n\t return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n\t }\n\t }\n\t\n\t // This function is used recursively from\n\t // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n\t // don't want to throw if we can't find the source - we just want to\n\t // return null, so we provide a flag to exit gracefully.\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tBasicSourceMapConsumer.prototype.generatedPositionFor =\n\t function SourceMapConsumer_generatedPositionFor(aArgs) {\n\t var source = util.getArg(aArgs, 'source');\n\t source = this._findSourceIndex(source);\n\t if (source < 0) {\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t }\n\t\n\t var needle = {\n\t source: source,\n\t originalLine: util.getArg(aArgs, 'line'),\n\t originalColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (mapping.source === needle.source) {\n\t return {\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t };\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t };\n\t\n\texports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\t\n\t/**\n\t * An IndexedSourceMapConsumer instance represents a parsed source map which\n\t * we can query for information. It differs from BasicSourceMapConsumer in\n\t * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n\t * input.\n\t *\n\t * The first parameter is a raw source map (either as a JSON string, or already\n\t * parsed to an object). According to the spec for indexed source maps, they\n\t * have the following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - file: Optional. The generated file this source map is associated with.\n\t * - sections: A list of section definitions.\n\t *\n\t * Each value under the \"sections\" field has two fields:\n\t * - offset: The offset into the original specified at which this section\n\t * begins to apply, defined as an object with a \"line\" and \"column\"\n\t * field.\n\t * - map: A source map definition. This source map could also be indexed,\n\t * but doesn't have to be.\n\t *\n\t * Instead of the \"map\" field, it's also possible to have a \"url\" field\n\t * specifying a URL to retrieve a source map from, but that's currently\n\t * unsupported.\n\t *\n\t * Here's an example source map, taken from the source map spec[0], but\n\t * modified to omit a section which uses the \"url\" field.\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"app.js\",\n\t * sections: [{\n\t * offset: {line:100, column:10},\n\t * map: {\n\t * version : 3,\n\t * file: \"section.js\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AAAA,E;;ABCDE;\"\n\t * }\n\t * }],\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n\t */\n\tfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sections = util.getArg(sourceMap, 'sections');\n\t\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t this._sources = new ArraySet();\n\t this._names = new ArraySet();\n\t\n\t var lastOffset = {\n\t line: -1,\n\t column: 0\n\t };\n\t this._sections = sections.map(function (s) {\n\t if (s.url) {\n\t // The url field will require support for asynchronicity.\n\t // See https://github.com/mozilla/source-map/issues/16\n\t throw new Error('Support for url field in sections not implemented.');\n\t }\n\t var offset = util.getArg(s, 'offset');\n\t var offsetLine = util.getArg(offset, 'line');\n\t var offsetColumn = util.getArg(offset, 'column');\n\t\n\t if (offsetLine < lastOffset.line ||\n\t (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n\t throw new Error('Section offsets must be ordered and non-overlapping.');\n\t }\n\t lastOffset = offset;\n\t\n\t return {\n\t generatedOffset: {\n\t // The offset fields are 0-based, but we use 1-based indices when\n\t // encoding/decoding from VLQ.\n\t generatedLine: offsetLine + 1,\n\t generatedColumn: offsetColumn + 1\n\t },\n\t consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n\t }\n\t });\n\t}\n\t\n\tIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tIndexedSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t var sources = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n\t sources.push(this._sections[i].consumer.sources[j]);\n\t }\n\t }\n\t return sources;\n\t }\n\t});\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tIndexedSourceMapConsumer.prototype.originalPositionFor =\n\t function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t // Find the section containing the generated position we're trying to map\n\t // to an original position.\n\t var sectionIndex = binarySearch.search(needle, this._sections,\n\t function(needle, section) {\n\t var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n\t if (cmp) {\n\t return cmp;\n\t }\n\t\n\t return (needle.generatedColumn -\n\t section.generatedOffset.generatedColumn);\n\t });\n\t var section = this._sections[sectionIndex];\n\t\n\t if (!section) {\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t }\n\t\n\t return section.consumer.originalPositionFor({\n\t line: needle.generatedLine -\n\t (section.generatedOffset.generatedLine - 1),\n\t column: needle.generatedColumn -\n\t (section.generatedOffset.generatedLine === needle.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t bias: aArgs.bias\n\t });\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n\t return this._sections.every(function (s) {\n\t return s.consumer.hasContentsOfAllSources();\n\t });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tIndexedSourceMapConsumer.prototype.sourceContentFor =\n\t function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t var content = section.consumer.sourceContentFor(aSource, true);\n\t if (content) {\n\t return content;\n\t }\n\t }\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based. \n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tIndexedSourceMapConsumer.prototype.generatedPositionFor =\n\t function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t // Only consider this section if the requested source is in the list of\n\t // sources of the consumer.\n\t if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n\t continue;\n\t }\n\t var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n\t if (generatedPosition) {\n\t var ret = {\n\t line: generatedPosition.line +\n\t (section.generatedOffset.generatedLine - 1),\n\t column: generatedPosition.column +\n\t (section.generatedOffset.generatedLine === generatedPosition.line\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0)\n\t };\n\t return ret;\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null\n\t };\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tIndexedSourceMapConsumer.prototype._parseMappings =\n\t function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t this.__generatedMappings = [];\n\t this.__originalMappings = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t var sectionMappings = section.consumer._generatedMappings;\n\t for (var j = 0; j < sectionMappings.length; j++) {\n\t var mapping = sectionMappings[j];\n\t\n\t var source = section.consumer._sources.at(mapping.source);\n\t source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n\t this._sources.add(source);\n\t source = this._sources.indexOf(source);\n\t\n\t var name = null;\n\t if (mapping.name) {\n\t name = section.consumer._names.at(mapping.name);\n\t this._names.add(name);\n\t name = this._names.indexOf(name);\n\t }\n\t\n\t // The mappings coming from the consumer for the section have\n\t // generated positions relative to the start of the section, so we\n\t // need to offset them to be relative to the start of the concatenated\n\t // generated file.\n\t var adjustedMapping = {\n\t source: source,\n\t generatedLine: mapping.generatedLine +\n\t (section.generatedOffset.generatedLine - 1),\n\t generatedColumn: mapping.generatedColumn +\n\t (section.generatedOffset.generatedLine === mapping.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: name\n\t };\n\t\n\t this.__generatedMappings.push(adjustedMapping);\n\t if (typeof adjustedMapping.originalLine === 'number') {\n\t this.__originalMappings.push(adjustedMapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t quickSort(this.__originalMappings, util.compareByOriginalPositions);\n\t };\n\t\n\texports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\texports.GREATEST_LOWER_BOUND = 1;\n\texports.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Recursive implementation of binary search.\n\t *\n\t * @param aLow Indices here and lower do not contain the needle.\n\t * @param aHigh Indices here and higher do not contain the needle.\n\t * @param aNeedle The element being searched for.\n\t * @param aHaystack The non-empty array being searched.\n\t * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t */\n\tfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n\t // This function terminates when one of the following is true:\n\t //\n\t // 1. We find the exact element we are looking for.\n\t //\n\t // 2. We did not find the exact element, but we can return the index of\n\t // the next-closest element.\n\t //\n\t // 3. We did not find the exact element, and there is no next-closest\n\t // element than the one we are searching for, so we return -1.\n\t var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n\t var cmp = aCompare(aNeedle, aHaystack[mid], true);\n\t if (cmp === 0) {\n\t // Found the element we are looking for.\n\t return mid;\n\t }\n\t else if (cmp > 0) {\n\t // Our needle is greater than aHaystack[mid].\n\t if (aHigh - mid > 1) {\n\t // The element is in the upper half.\n\t return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // The exact needle element was not found in this haystack. Determine if\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return aHigh < aHaystack.length ? aHigh : -1;\n\t } else {\n\t return mid;\n\t }\n\t }\n\t else {\n\t // Our needle is less than aHaystack[mid].\n\t if (mid - aLow > 1) {\n\t // The element is in the lower half.\n\t return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return mid;\n\t } else {\n\t return aLow < 0 ? -1 : aLow;\n\t }\n\t }\n\t}\n\t\n\t/**\n\t * This is an implementation of binary search which will always try and return\n\t * the index of the closest element if there is no exact hit. This is because\n\t * mappings between original and generated line/col pairs are single points,\n\t * and there is an implicit region between each of them, so a miss just means\n\t * that you aren't on the very start of a region.\n\t *\n\t * @param aNeedle The element you are looking for.\n\t * @param aHaystack The array that is being searched.\n\t * @param aCompare A function which takes the needle and an element in the\n\t * array and returns -1, 0, or 1 depending on whether the needle is less\n\t * than, equal to, or greater than the element, respectively.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n\t */\n\texports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n\t if (aHaystack.length === 0) {\n\t return -1;\n\t }\n\t\n\t var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n\t aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n\t if (index < 0) {\n\t return -1;\n\t }\n\t\n\t // We have found either the exact element, or the next-closest element than\n\t // the one we are searching for. However, there may be more than one such\n\t // element. Make sure we always return the smallest of these.\n\t while (index - 1 >= 0) {\n\t if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n\t break;\n\t }\n\t --index;\n\t }\n\t\n\t return index;\n\t};\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t// It turns out that some (most?) JavaScript engines don't self-host\n\t// `Array.prototype.sort`. This makes sense because C++ will likely remain\n\t// faster than JS when doing raw CPU-intensive sorting. However, when using a\n\t// custom comparator function, calling back and forth between the VM's C++ and\n\t// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n\t// worse generated code for the comparator function than would be optimal. In\n\t// fact, when sorting with a comparator, these costs outweigh the benefits of\n\t// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n\t// a ~3500ms mean speed-up in `bench/bench.html`.\n\t\n\t/**\n\t * Swap the elements indexed by `x` and `y` in the array `ary`.\n\t *\n\t * @param {Array} ary\n\t * The array.\n\t * @param {Number} x\n\t * The index of the first item.\n\t * @param {Number} y\n\t * The index of the second item.\n\t */\n\tfunction swap(ary, x, y) {\n\t var temp = ary[x];\n\t ary[x] = ary[y];\n\t ary[y] = temp;\n\t}\n\t\n\t/**\n\t * Returns a random integer within the range `low .. high` inclusive.\n\t *\n\t * @param {Number} low\n\t * The lower bound on the range.\n\t * @param {Number} high\n\t * The upper bound on the range.\n\t */\n\tfunction randomIntInRange(low, high) {\n\t return Math.round(low + (Math.random() * (high - low)));\n\t}\n\t\n\t/**\n\t * The Quick Sort algorithm.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t * @param {Number} p\n\t * Start index of the array\n\t * @param {Number} r\n\t * End index of the array\n\t */\n\tfunction doQuickSort(ary, comparator, p, r) {\n\t // If our lower bound is less than our upper bound, we (1) partition the\n\t // array into two pieces and (2) recurse on each half. If it is not, this is\n\t // the empty array and our base case.\n\t\n\t if (p < r) {\n\t // (1) Partitioning.\n\t //\n\t // The partitioning chooses a pivot between `p` and `r` and moves all\n\t // elements that are less than or equal to the pivot to the before it, and\n\t // all the elements that are greater than it after it. The effect is that\n\t // once partition is done, the pivot is in the exact place it will be when\n\t // the array is put in sorted order, and it will not need to be moved\n\t // again. This runs in O(n) time.\n\t\n\t // Always choose a random pivot so that an input array which is reverse\n\t // sorted does not cause O(n^2) running time.\n\t var pivotIndex = randomIntInRange(p, r);\n\t var i = p - 1;\n\t\n\t swap(ary, pivotIndex, r);\n\t var pivot = ary[r];\n\t\n\t // Immediately after `j` is incremented in this loop, the following hold\n\t // true:\n\t //\n\t // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n\t //\n\t // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n\t for (var j = p; j < r; j++) {\n\t if (comparator(ary[j], pivot) <= 0) {\n\t i += 1;\n\t swap(ary, i, j);\n\t }\n\t }\n\t\n\t swap(ary, i + 1, j);\n\t var q = i + 1;\n\t\n\t // (2) Recurse on each half.\n\t\n\t doQuickSort(ary, comparator, p, q - 1);\n\t doQuickSort(ary, comparator, q + 1, r);\n\t }\n\t}\n\t\n\t/**\n\t * Sort the given array in-place with the given comparator function.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t */\n\texports.quickSort = function (ary, comparator) {\n\t doQuickSort(ary, comparator, 0, ary.length - 1);\n\t};\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;\n\tvar util = __webpack_require__(4);\n\t\n\t// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n\t// operating systems these days (capturing the result).\n\tvar REGEX_NEWLINE = /(\\r?\\n)/;\n\t\n\t// Newline character code for charCodeAt() comparisons\n\tvar NEWLINE_CODE = 10;\n\t\n\t// Private symbol for identifying `SourceNode`s when multiple versions of\n\t// the source-map library are loaded. This MUST NOT CHANGE across\n\t// versions!\n\tvar isSourceNode = \"$$$isSourceNode$$$\";\n\t\n\t/**\n\t * SourceNodes provide a way to abstract over interpolating/concatenating\n\t * snippets of generated JavaScript source code while maintaining the line and\n\t * column information associated with the original source code.\n\t *\n\t * @param aLine The original line number.\n\t * @param aColumn The original column number.\n\t * @param aSource The original source's filename.\n\t * @param aChunks Optional. An array of strings which are snippets of\n\t * generated JS, or other SourceNodes.\n\t * @param aName The original identifier.\n\t */\n\tfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n\t this.children = [];\n\t this.sourceContents = {};\n\t this.line = aLine == null ? null : aLine;\n\t this.column = aColumn == null ? null : aColumn;\n\t this.source = aSource == null ? null : aSource;\n\t this.name = aName == null ? null : aName;\n\t this[isSourceNode] = true;\n\t if (aChunks != null) this.add(aChunks);\n\t}\n\t\n\t/**\n\t * Creates a SourceNode from generated code and a SourceMapConsumer.\n\t *\n\t * @param aGeneratedCode The generated code\n\t * @param aSourceMapConsumer The SourceMap for the generated code\n\t * @param aRelativePath Optional. The path that relative sources in the\n\t * SourceMapConsumer should be relative to.\n\t */\n\tSourceNode.fromStringWithSourceMap =\n\t function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n\t // The SourceNode we want to fill with the generated code\n\t // and the SourceMap\n\t var node = new SourceNode();\n\t\n\t // All even indices of this array are one line of the generated code,\n\t // while all odd indices are the newlines between two adjacent lines\n\t // (since `REGEX_NEWLINE` captures its match).\n\t // Processed fragments are accessed by calling `shiftNextLine`.\n\t var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n\t var remainingLinesIndex = 0;\n\t var shiftNextLine = function() {\n\t var lineContents = getNextLine();\n\t // The last line of a file might not have a newline.\n\t var newLine = getNextLine() || \"\";\n\t return lineContents + newLine;\n\t\n\t function getNextLine() {\n\t return remainingLinesIndex < remainingLines.length ?\n\t remainingLines[remainingLinesIndex++] : undefined;\n\t }\n\t };\n\t\n\t // We need to remember the position of \"remainingLines\"\n\t var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\t\n\t // The generate SourceNodes we need a code range.\n\t // To extract it current and last mapping is used.\n\t // Here we store the last mapping.\n\t var lastMapping = null;\n\t\n\t aSourceMapConsumer.eachMapping(function (mapping) {\n\t if (lastMapping !== null) {\n\t // We add the code from \"lastMapping\" to \"mapping\":\n\t // First check if there is a new line in between.\n\t if (lastGeneratedLine < mapping.generatedLine) {\n\t // Associate first line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t lastGeneratedLine++;\n\t lastGeneratedColumn = 0;\n\t // The remaining code is added without mapping\n\t } else {\n\t // There is no new line in between.\n\t // Associate the code between \"lastGeneratedColumn\" and\n\t // \"mapping.generatedColumn\" with \"lastMapping\"\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t var code = nextLine.substr(0, mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t addMappingWithCode(lastMapping, code);\n\t // No more remaining code, continue\n\t lastMapping = mapping;\n\t return;\n\t }\n\t }\n\t // We add the generated code until the first mapping\n\t // to the SourceNode without any mapping.\n\t // Each line is added as separate string.\n\t while (lastGeneratedLine < mapping.generatedLine) {\n\t node.add(shiftNextLine());\n\t lastGeneratedLine++;\n\t }\n\t if (lastGeneratedColumn < mapping.generatedColumn) {\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t node.add(nextLine.substr(0, mapping.generatedColumn));\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t }\n\t lastMapping = mapping;\n\t }, this);\n\t // We have processed all mappings.\n\t if (remainingLinesIndex < remainingLines.length) {\n\t if (lastMapping) {\n\t // Associate the remaining code in the current line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t }\n\t // and add the remaining lines without any mapping\n\t node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n\t }\n\t\n\t // Copy sourcesContent into SourceNode\n\t aSourceMapConsumer.sources.forEach(function (sourceFile) {\n\t var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n\t if (content != null) {\n\t if (aRelativePath != null) {\n\t sourceFile = util.join(aRelativePath, sourceFile);\n\t }\n\t node.setSourceContent(sourceFile, content);\n\t }\n\t });\n\t\n\t return node;\n\t\n\t function addMappingWithCode(mapping, code) {\n\t if (mapping === null || mapping.source === undefined) {\n\t node.add(code);\n\t } else {\n\t var source = aRelativePath\n\t ? util.join(aRelativePath, mapping.source)\n\t : mapping.source;\n\t node.add(new SourceNode(mapping.originalLine,\n\t mapping.originalColumn,\n\t source,\n\t code,\n\t mapping.name));\n\t }\n\t }\n\t };\n\t\n\t/**\n\t * Add a chunk of generated JS to this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.add = function SourceNode_add(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t aChunk.forEach(function (chunk) {\n\t this.add(chunk);\n\t }, this);\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t if (aChunk) {\n\t this.children.push(aChunk);\n\t }\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a chunk of generated JS to the beginning of this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t for (var i = aChunk.length-1; i >= 0; i--) {\n\t this.prepend(aChunk[i]);\n\t }\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t this.children.unshift(aChunk);\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Walk over the tree of JS snippets in this node and its children. The\n\t * walking function is called once for each snippet of JS and is passed that\n\t * snippet and the its original associated source's line/column location.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n\t var chunk;\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t chunk = this.children[i];\n\t if (chunk[isSourceNode]) {\n\t chunk.walk(aFn);\n\t }\n\t else {\n\t if (chunk !== '') {\n\t aFn(chunk, { source: this.source,\n\t line: this.line,\n\t column: this.column,\n\t name: this.name });\n\t }\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n\t * each of `this.children`.\n\t *\n\t * @param aSep The separator.\n\t */\n\tSourceNode.prototype.join = function SourceNode_join(aSep) {\n\t var newChildren;\n\t var i;\n\t var len = this.children.length;\n\t if (len > 0) {\n\t newChildren = [];\n\t for (i = 0; i < len-1; i++) {\n\t newChildren.push(this.children[i]);\n\t newChildren.push(aSep);\n\t }\n\t newChildren.push(this.children[i]);\n\t this.children = newChildren;\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Call String.prototype.replace on the very right-most source snippet. Useful\n\t * for trimming whitespace from the end of a source node, etc.\n\t *\n\t * @param aPattern The pattern to replace.\n\t * @param aReplacement The thing to replace the pattern with.\n\t */\n\tSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n\t var lastChild = this.children[this.children.length - 1];\n\t if (lastChild[isSourceNode]) {\n\t lastChild.replaceRight(aPattern, aReplacement);\n\t }\n\t else if (typeof lastChild === 'string') {\n\t this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n\t }\n\t else {\n\t this.children.push(''.replace(aPattern, aReplacement));\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Set the source content for a source file. This will be added to the SourceMapGenerator\n\t * in the sourcesContent field.\n\t *\n\t * @param aSourceFile The filename of the source file\n\t * @param aSourceContent The content of the source file\n\t */\n\tSourceNode.prototype.setSourceContent =\n\t function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n\t this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n\t };\n\t\n\t/**\n\t * Walk over the tree of SourceNodes. The walking function is called for each\n\t * source file content and is passed the filename and source content.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walkSourceContents =\n\t function SourceNode_walkSourceContents(aFn) {\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t if (this.children[i][isSourceNode]) {\n\t this.children[i].walkSourceContents(aFn);\n\t }\n\t }\n\t\n\t var sources = Object.keys(this.sourceContents);\n\t for (var i = 0, len = sources.length; i < len; i++) {\n\t aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n\t }\n\t };\n\t\n\t/**\n\t * Return the string representation of this source node. Walks over the tree\n\t * and concatenates all the various snippets together to one string.\n\t */\n\tSourceNode.prototype.toString = function SourceNode_toString() {\n\t var str = \"\";\n\t this.walk(function (chunk) {\n\t str += chunk;\n\t });\n\t return str;\n\t};\n\t\n\t/**\n\t * Returns the string representation of this source node along with a source\n\t * map.\n\t */\n\tSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n\t var generated = {\n\t code: \"\",\n\t line: 1,\n\t column: 0\n\t };\n\t var map = new SourceMapGenerator(aArgs);\n\t var sourceMappingActive = false;\n\t var lastOriginalSource = null;\n\t var lastOriginalLine = null;\n\t var lastOriginalColumn = null;\n\t var lastOriginalName = null;\n\t this.walk(function (chunk, original) {\n\t generated.code += chunk;\n\t if (original.source !== null\n\t && original.line !== null\n\t && original.column !== null) {\n\t if(lastOriginalSource !== original.source\n\t || lastOriginalLine !== original.line\n\t || lastOriginalColumn !== original.column\n\t || lastOriginalName !== original.name) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t lastOriginalSource = original.source;\n\t lastOriginalLine = original.line;\n\t lastOriginalColumn = original.column;\n\t lastOriginalName = original.name;\n\t sourceMappingActive = true;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t }\n\t });\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t }\n\t for (var idx = 0, length = chunk.length; idx < length; idx++) {\n\t if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n\t generated.line++;\n\t generated.column = 0;\n\t // Mappings end at eol\n\t if (idx + 1 === length) {\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t } else {\n\t generated.column++;\n\t }\n\t }\n\t });\n\t this.walkSourceContents(function (sourceFile, sourceContent) {\n\t map.setSourceContent(sourceFile, sourceContent);\n\t });\n\t\n\t return { code: generated.code, map: map };\n\t};\n\t\n\texports.SourceNode = SourceNode;\n\n\n/***/ })\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// source-map.min.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 0fd5815da764db5fb9fe","/*\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 = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./source-map.js\n// module id = 0\n// module chunks = 0","/* -*- 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 = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').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 sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\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\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-generator.js\n// module id = 1\n// module chunks = 0","/* -*- 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 = require('./base64');\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\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64-vlq.js\n// module id = 2\n// module chunks = 0","/* -*- 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\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64.js\n// module id = 3\n// module chunks = 0","/* -*- 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+))?(.*)$/;\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) === '/' || urlRegexp.test(aPath);\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 = 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 || 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 strcmp(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 = 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.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\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 * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/util.js\n// module id = 4\n// module chunks = 0","/* -*- 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 = require('./util');\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\n//////////////////\n// WEBPACK FOOTER\n// ./lib/array-set.js\n// module id = 5\n// module chunks = 0","/* -*- 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 = require('./util');\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\n//////////////////\n// WEBPACK FOOTER\n// ./lib/mapping-list.js\n// module id = 6\n// module chunks = 0","/* -*- 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 = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\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 configurable: true,\n enumerable: true,\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 configurable: true,\n enumerable: true,\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 source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\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. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\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. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\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 needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\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 first 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 * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\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 if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\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._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\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 smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\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._absoluteSources.slice();\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. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\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. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\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 source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\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 var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\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 = relativeSource.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(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\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('\"' + relativeSource + '\" 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. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\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. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\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 first 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 * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\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'), aSourceMapURL)\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. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\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. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\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. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\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._findSourceIndex(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 source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\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\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-consumer.js\n// module id = 7\n// module chunks = 0","/* -*- 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\n//////////////////\n// WEBPACK FOOTER\n// ./lib/binary-search.js\n// module id = 8\n// module chunks = 0","/* -*- 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\n//////////////////\n// WEBPACK FOOTER\n// ./lib/quick-sort.js\n// module id = 9\n// module chunks = 0","/* -*- 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 = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\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\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-node.js\n// module id = 10\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/source-map/lib/array-set.js b/node_modules/source-map/lib/array-set.js new file mode 100644 index 0000000..fbd5c81 --- /dev/null +++ b/node_modules/source-map/lib/array-set.js @@ -0,0 +1,121 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/node_modules/source-map/lib/base64-vlq.js b/node_modules/source-map/lib/base64-vlq.js new file mode 100644 index 0000000..612b404 --- /dev/null +++ b/node_modules/source-map/lib/base64-vlq.js @@ -0,0 +1,140 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * * Neither the name of Google Inc. 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 + * OWNER 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. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/node_modules/source-map/lib/base64.js b/node_modules/source-map/lib/base64.js new file mode 100644 index 0000000..8aa86b3 --- /dev/null +++ b/node_modules/source-map/lib/base64.js @@ -0,0 +1,67 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/node_modules/source-map/lib/binary-search.js b/node_modules/source-map/lib/binary-search.js new file mode 100644 index 0000000..010ac94 --- /dev/null +++ b/node_modules/source-map/lib/binary-search.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/node_modules/source-map/lib/mapping-list.js b/node_modules/source-map/lib/mapping-list.js new file mode 100644 index 0000000..06d1274 --- /dev/null +++ b/node_modules/source-map/lib/mapping-list.js @@ -0,0 +1,79 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/node_modules/source-map/lib/quick-sort.js b/node_modules/source-map/lib/quick-sort.js new file mode 100644 index 0000000..6a7caad --- /dev/null +++ b/node_modules/source-map/lib/quick-sort.js @@ -0,0 +1,114 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; diff --git a/node_modules/source-map/lib/source-map-consumer.js b/node_modules/source-map/lib/source-map-consumer.js new file mode 100644 index 0000000..7b99d1d --- /dev/null +++ b/node_modules/source-map/lib/source-map-consumer.js @@ -0,0 +1,1145 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/node_modules/source-map/lib/source-map-generator.js b/node_modules/source-map/lib/source-map-generator.js new file mode 100644 index 0000000..508bcfb --- /dev/null +++ b/node_modules/source-map/lib/source-map-generator.js @@ -0,0 +1,425 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/node_modules/source-map/lib/source-node.js b/node_modules/source-map/lib/source-node.js new file mode 100644 index 0000000..8bcdbe3 --- /dev/null +++ b/node_modules/source-map/lib/source-node.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; diff --git a/node_modules/source-map/lib/util.js b/node_modules/source-map/lib/util.js new file mode 100644 index 0000000..3ca92e5 --- /dev/null +++ b/node_modules/source-map/lib/util.js @@ -0,0 +1,488 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/node_modules/source-map/package.json b/node_modules/source-map/package.json new file mode 100644 index 0000000..2466341 --- /dev/null +++ b/node_modules/source-map/package.json @@ -0,0 +1,73 @@ +{ + "name": "source-map", + "description": "Generates and consumes source maps", + "version": "0.6.1", + "homepage": "https://github.com/mozilla/source-map", + "author": "Nick Fitzgerald ", + "contributors": [ + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": { + "type": "git", + "url": "http://github.com/mozilla/source-map.git" + }, + "main": "./source-map.js", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/", + "dist/source-map.debug.js", + "dist/source-map.js", + "dist/source-map.min.js", + "dist/source-map.min.js.map" + ], + "engines": { + "node": ">=0.10.0" + }, + "license": "BSD-3-Clause", + "scripts": { + "test": "npm run build && node test/run-tests.js", + "build": "webpack --color", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "devDependencies": { + "doctoc": "^0.15.0", + "webpack": "^1.12.0" + }, + "typings": "source-map" +} diff --git a/node_modules/source-map/source-map.d.ts b/node_modules/source-map/source-map.d.ts new file mode 100644 index 0000000..8f972b0 --- /dev/null +++ b/node_modules/source-map/source-map.d.ts @@ -0,0 +1,98 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +export interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string; + generatedLine: number; + generatedColumn: number; + originalLine: number; + originalColumn: number; + name: string; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + constructor(rawSourceMap: RawSourceMap); + computeColumnSpans(): void; + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; + hasContentsOfAllSources(): boolean; + sourceContentFor(source: string, returnNullOnMissing?: boolean): string; + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface Mapping { + generated: Position; + original: Position; + source: string; + name?: string; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + toString(): string; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + add(chunk: string): void; + prepend(chunk: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; + toString(): string; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/node_modules/source-map/source-map.js b/node_modules/source-map/source-map.js new file mode 100644 index 0000000..bc88fe8 --- /dev/null +++ b/node_modules/source-map/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/node_modules/sourcemap-codec/CHANGELOG.md b/node_modules/sourcemap-codec/CHANGELOG.md new file mode 100644 index 0000000..e5ab34a --- /dev/null +++ b/node_modules/sourcemap-codec/CHANGELOG.md @@ -0,0 +1,64 @@ +# sourcemap-codec changelog + +## 1.4.8 + +* Performance boost ([#80](https://github.com/Rich-Harris/sourcemap-codec/pull/80)) + +## 1.4.7 + +* Include .map files in package ([#73](https://github.com/Rich-Harris/sourcemap-codec/issues/73)) + +## 1.4.6 + +* Use arrays instead of typed arrays ([#79](https://github.com/Rich-Harris/sourcemap-codec/pull/79)) + +## 1.4.5 + +* Handle overflow cases ([#78](https://github.com/Rich-Harris/sourcemap-codec/pull/78)) + +## 1.4.4 + +* Use Uint32Array, yikes ([#77](https://github.com/Rich-Harris/sourcemap-codec/pull/77)) + +## 1.4.3 + +* Use Uint16Array to prevent overflow ([#75](https://github.com/Rich-Harris/sourcemap-codec/pull/75)) + +## 1.4.2 + +* GO EVEN FASTER ([#74](https://github.com/Rich-Harris/sourcemap-codec/pull/74)) + +## 1.4.1 + +* GO FASTER ([#71](https://github.com/Rich-Harris/sourcemap-codec/pull/71)) + +## 1.4.0 + +* Add TypeScript declarations ([#70](https://github.com/Rich-Harris/sourcemap-codec/pull/70)) + +## 1.3.1 + +* Update build process, expose `pkg.module` + +## 1.3.0 + +* Update build process + +## 1.2.1 + +* Add dist files to npm package + +## 1.2.0 + +* Add ES6 build +* Update dependencies +* Add test coverage + +## 1.1.0 + +* Fix bug with lines containing single-character segments +* Add tests + +## 1.0.0 + +* First release diff --git a/node_modules/sourcemap-codec/LICENSE b/node_modules/sourcemap-codec/LICENSE new file mode 100644 index 0000000..a331065 --- /dev/null +++ b/node_modules/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/sourcemap-codec/README.md b/node_modules/sourcemap-codec/README.md new file mode 100644 index 0000000..e4373aa --- /dev/null +++ b/node_modules/sourcemap-codec/README.md @@ -0,0 +1,63 @@ +# 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 sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from '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' ); +``` + + +# License + +MIT diff --git a/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js b/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js new file mode 100644 index 0000000..f5e7d06 --- /dev/null +++ b/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js @@ -0,0 +1,124 @@ +var charToInteger = {}; +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +for (var i = 0; i < chars.length; i++) { + charToInteger[chars.charCodeAt(i)] = i; +} +function decode(mappings) { + var decoded = []; + var line = []; + var segment = [ + 0, + 0, + 0, + 0, + 0, + ]; + var j = 0; + for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) { + var c = mappings.charCodeAt(i); + if (c === 44) { // "," + segmentify(line, segment, j); + j = 0; + } + else if (c === 59) { // ";" + segmentify(line, segment, j); + j = 0; + decoded.push(line); + line = []; + segment[0] = 0; + } + else { + var integer = charToInteger[c]; + if (integer === undefined) { + throw new Error('Invalid character (' + String.fromCharCode(c) + ')'); + } + var hasContinuationBit = integer & 32; + integer &= 31; + value += integer << shift; + if (hasContinuationBit) { + shift += 5; + } + else { + var shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = value === 0 ? -0x80000000 : -value; + } + segment[j] += value; + j++; + value = shift = 0; // reset + } + } + } + segmentify(line, segment, j); + decoded.push(line); + return decoded; +} +function segmentify(line, segment, j) { + // This looks ugly, but we're creating specialized arrays with a specific + // length. This is much faster than creating a new array (which v8 expands to + // a capacity of 17 after pushing the first item), or slicing out a subarray + // (which is slow). Length 4 is assumed to be the most frequent, followed by + // length 5 (since not everything will have an associated name), followed by + // length 1 (it's probably rare for a source substring to not have an + // associated segment data). + if (j === 4) + line.push([segment[0], segment[1], segment[2], segment[3]]); + else if (j === 5) + line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]); + else if (j === 1) + line.push([segment[0]]); +} +function encode(decoded) { + var sourceFileIndex = 0; // second field + var sourceCodeLine = 0; // third field + var sourceCodeColumn = 0; // fourth field + var nameIndex = 0; // fifth field + var mappings = ''; + for (var i = 0; i < decoded.length; i++) { + var line = decoded[i]; + if (i > 0) + mappings += ';'; + if (line.length === 0) + continue; + var generatedCodeColumn = 0; // first field + var lineMappings = []; + for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { + var segment = line_1[_i]; + var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn); + generatedCodeColumn = segment[0]; + if (segment.length > 1) { + segmentMappings += + encodeInteger(segment[1] - sourceFileIndex) + + encodeInteger(segment[2] - sourceCodeLine) + + encodeInteger(segment[3] - sourceCodeColumn); + sourceFileIndex = segment[1]; + sourceCodeLine = segment[2]; + sourceCodeColumn = segment[3]; + } + if (segment.length === 5) { + segmentMappings += encodeInteger(segment[4] - nameIndex); + nameIndex = segment[4]; + } + lineMappings.push(segmentMappings); + } + mappings += lineMappings.join(','); + } + return mappings; +} +function encodeInteger(num) { + var result = ''; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + var clamped = num & 31; + num >>>= 5; + if (num > 0) { + clamped |= 32; + } + result += chars[clamped]; + } while (num > 0); + return result; +} + +export { decode, encode }; +//# sourceMappingURL=sourcemap-codec.es.js.map diff --git a/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js.map b/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js.map new file mode 100644 index 0000000..f2cab32 --- /dev/null +++ b/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.es.js","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n\t| [number]\n\t| [number, number, number, number]\n\t| [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst charToInteger: { [charCode: number]: number } = {};\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfor (let i = 0; i < chars.length; i++) {\n\tcharToInteger[chars.charCodeAt(i)] = i;\n}\n\nexport function decode(mappings: string): SourceMapMappings {\n\tconst decoded: SourceMapMappings = [];\n\tlet line: SourceMapLine = [];\n\tconst segment: SourceMapSegment = [\n\t\t0, // generated code column\n\t\t0, // source file index\n\t\t0, // source code line\n\t\t0, // source code column\n\t\t0, // name index\n\t];\n\n\tlet j = 0;\n\tfor (let i = 0, shift = 0, value = 0; i < mappings.length; i++) {\n\t\tconst c = mappings.charCodeAt(i);\n\n\t\tif (c === 44) { // \",\"\n\t\t\tsegmentify(line, segment, j);\n\t\t\tj = 0;\n\n\t\t} else if (c === 59) { // \";\"\n\t\t\tsegmentify(line, segment, j);\n\t\t\tj = 0;\n\t\t\tdecoded.push(line);\n\t\t\tline = [];\n\t\t\tsegment[0] = 0;\n\n\t\t} else {\n\t\t\tlet integer = charToInteger[c];\n\t\t\tif (integer === undefined) {\n\t\t\t\tthrow new Error('Invalid character (' + String.fromCharCode(c) + ')');\n\t\t\t}\n\n\t\t\tconst hasContinuationBit = integer & 32;\n\n\t\t\tinteger &= 31;\n\t\t\tvalue += integer << shift;\n\n\t\t\tif (hasContinuationBit) {\n\t\t\t\tshift += 5;\n\t\t\t} else {\n\t\t\t\tconst shouldNegate = value & 1;\n\t\t\t\tvalue >>>= 1;\n\n\t\t\t\tif (shouldNegate) {\n\t\t\t\t\tvalue = value === 0 ? -0x80000000 : -value;\n\t\t\t\t}\n\n\t\t\t\tsegment[j] += value;\n\t\t\t\tj++;\n\t\t\t\tvalue = shift = 0; // reset\n\t\t\t}\n\t\t}\n\t}\n\n\tsegmentify(line, segment, j);\n\tdecoded.push(line);\n\n\treturn decoded;\n}\n\nfunction segmentify(line: SourceMapSegment[], segment: SourceMapSegment, j: number) {\n\t// This looks ugly, but we're creating specialized arrays with a specific\n\t// length. This is much faster than creating a new array (which v8 expands to\n\t// a capacity of 17 after pushing the first item), or slicing out a subarray\n\t// (which is slow). Length 4 is assumed to be the most frequent, followed by\n\t// length 5 (since not everything will have an associated name), followed by\n\t// length 1 (it's probably rare for a source substring to not have an\n\t// associated segment data).\n\tif (j === 4) line.push([segment[0], segment[1], segment[2], segment[3]]);\n\telse if (j === 5) line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);\n\telse if (j === 1) line.push([segment[0]]);\n}\n\nexport function encode(decoded: SourceMapMappings): string {\n\tlet sourceFileIndex = 0; // second field\n\tlet sourceCodeLine = 0; // third field\n\tlet sourceCodeColumn = 0; // fourth field\n\tlet nameIndex = 0; // fifth field\n\tlet mappings = '';\n\n\tfor (let i = 0; i < decoded.length; i++) {\n\t\tconst line = decoded[i];\n\t\tif (i > 0) mappings += ';';\n\t\tif (line.length === 0) continue;\n\n\t\tlet generatedCodeColumn = 0; // first field\n\n\t\tconst lineMappings: string[] = [];\n\n\t\tfor (const segment of line) {\n\t\t\tlet segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);\n\t\t\tgeneratedCodeColumn = segment[0];\n\n\t\t\tif (segment.length > 1) {\n\t\t\t\tsegmentMappings +=\n\t\t\t\t\tencodeInteger(segment[1] - sourceFileIndex) +\n\t\t\t\t\tencodeInteger(segment[2] - sourceCodeLine) +\n\t\t\t\t\tencodeInteger(segment[3] - sourceCodeColumn);\n\n\t\t\t\tsourceFileIndex = segment[1];\n\t\t\t\tsourceCodeLine = segment[2];\n\t\t\t\tsourceCodeColumn = segment[3];\n\t\t\t}\n\n\t\t\tif (segment.length === 5) {\n\t\t\t\tsegmentMappings += encodeInteger(segment[4] - nameIndex);\n\t\t\t\tnameIndex = segment[4];\n\t\t\t}\n\n\t\t\tlineMappings.push(segmentMappings);\n\t\t}\n\n\t\tmappings += lineMappings.join(',');\n\t}\n\n\treturn mappings;\n}\n\nfunction encodeInteger(num: number): string {\n\tvar result = '';\n\tnum = num < 0 ? (-num << 1) | 1 : num << 1;\n\tdo {\n\t\tvar clamped = num & 31;\n\t\tnum >>>= 5;\n\t\tif (num > 0) {\n\t\t\tclamped |= 32;\n\t\t}\n\t\tresult += chars[clamped];\n\t} while (num > 0);\n\n\treturn result;\n}\n"],"names":[],"mappings":"AAOA,IAAM,aAAa,GAAmC,EAAE,CAAC;AACzD,IAAM,KAAK,GAAG,mEAAmE,CAAC;AAElF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACtC,aAAa,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;CACvC;AAED,SAAgB,MAAM,CAAC,QAAgB;IACtC,IAAM,OAAO,GAAsB,EAAE,CAAC;IACtC,IAAI,IAAI,GAAkB,EAAE,CAAC;IAC7B,IAAM,OAAO,GAAqB;QACjC,CAAC;QACD,CAAC;QACD,CAAC;QACD,CAAC;QACD,CAAC;KACD,CAAC;IAEF,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAC/D,IAAM,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAEjC,IAAI,CAAC,KAAK,EAAE,EAAE;YACb,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YAC7B,CAAC,GAAG,CAAC,CAAC;SAEN;aAAM,IAAI,CAAC,KAAK,EAAE,EAAE;YACpB,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YAC7B,CAAC,GAAG,CAAC,CAAC;YACN,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnB,IAAI,GAAG,EAAE,CAAC;YACV,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;SAEf;aAAM;YACN,IAAI,OAAO,GAAG,aAAa,CAAC,CAAC,CAAC,CAAC;YAC/B,IAAI,OAAO,KAAK,SAAS,EAAE;gBAC1B,MAAM,IAAI,KAAK,CAAC,qBAAqB,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC;aACtE;YAED,IAAM,kBAAkB,GAAG,OAAO,GAAG,EAAE,CAAC;YAExC,OAAO,IAAI,EAAE,CAAC;YACd,KAAK,IAAI,OAAO,IAAI,KAAK,CAAC;YAE1B,IAAI,kBAAkB,EAAE;gBACvB,KAAK,IAAI,CAAC,CAAC;aACX;iBAAM;gBACN,IAAM,YAAY,GAAG,KAAK,GAAG,CAAC,CAAC;gBAC/B,KAAK,MAAM,CAAC,CAAC;gBAEb,IAAI,YAAY,EAAE;oBACjB,KAAK,GAAG,KAAK,KAAK,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,KAAK,CAAC;iBAC3C;gBAED,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC;gBACpB,CAAC,EAAE,CAAC;gBACJ,KAAK,GAAG,KAAK,GAAG,CAAC,CAAC;aAClB;SACD;KACD;IAED,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;IAC7B,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAEnB,OAAO,OAAO,CAAC;CACf;AAED,SAAS,UAAU,CAAC,IAAwB,EAAE,OAAyB,EAAE,CAAS;;;;;;;;IAQjF,IAAI,CAAC,KAAK,CAAC;QAAE,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SACpE,IAAI,CAAC,KAAK,CAAC;QAAE,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SACrF,IAAI,CAAC,KAAK,CAAC;QAAE,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAC1C;AAED,SAAgB,MAAM,CAAC,OAA0B;IAChD,IAAI,eAAe,GAAG,CAAC,CAAC;IACxB,IAAI,cAAc,GAAG,CAAC,CAAC;IACvB,IAAI,gBAAgB,GAAG,CAAC,CAAC;IACzB,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,IAAI,QAAQ,GAAG,EAAE,CAAC;IAElB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACxC,IAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,GAAG,CAAC;YAAE,QAAQ,IAAI,GAAG,CAAC;QAC3B,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QAEhC,IAAI,mBAAmB,GAAG,CAAC,CAAC;QAE5B,IAAM,YAAY,GAAa,EAAE,CAAC;QAElC,KAAsB,UAAI,EAAJ,aAAI,EAAJ,kBAAI,EAAJ,IAAI,EAAE;YAAvB,IAAM,OAAO,aAAA;YACjB,IAAI,eAAe,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAAC,CAAC;YACtE,mBAAmB,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YAEjC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;gBACvB,eAAe;oBACd,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,eAAe,CAAC;wBAC3C,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,cAAc,CAAC;wBAC1C,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAC,CAAC;gBAE9C,eAAe,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;gBAC7B,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;gBAC5B,gBAAgB,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;aAC9B;YAED,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;gBACzB,eAAe,IAAI,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;gBACzD,SAAS,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;aACvB;YAED,YAAY,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;SACnC;QAED,QAAQ,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;KACnC;IAED,OAAO,QAAQ,CAAC;CAChB;AAED,SAAS,aAAa,CAAC,GAAW;IACjC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;IAC3C,GAAG;QACF,IAAI,OAAO,GAAG,GAAG,GAAG,EAAE,CAAC;QACvB,GAAG,MAAM,CAAC,CAAC;QACX,IAAI,GAAG,GAAG,CAAC,EAAE;YACZ,OAAO,IAAI,EAAE,CAAC;SACd;QACD,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;KACzB,QAAQ,GAAG,GAAG,CAAC,EAAE;IAElB,OAAO,MAAM,CAAC;CACd;;;;"} \ No newline at end of file diff --git a/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..e305147 --- /dev/null +++ b/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,135 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.sourcemapCodec = {})); +}(this, function (exports) { 'use strict'; + + var charToInteger = {}; + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + for (var i = 0; i < chars.length; i++) { + charToInteger[chars.charCodeAt(i)] = i; + } + function decode(mappings) { + var decoded = []; + var line = []; + var segment = [ + 0, + 0, + 0, + 0, + 0, + ]; + var j = 0; + for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) { + var c = mappings.charCodeAt(i); + if (c === 44) { // "," + segmentify(line, segment, j); + j = 0; + } + else if (c === 59) { // ";" + segmentify(line, segment, j); + j = 0; + decoded.push(line); + line = []; + segment[0] = 0; + } + else { + var integer = charToInteger[c]; + if (integer === undefined) { + throw new Error('Invalid character (' + String.fromCharCode(c) + ')'); + } + var hasContinuationBit = integer & 32; + integer &= 31; + value += integer << shift; + if (hasContinuationBit) { + shift += 5; + } + else { + var shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = value === 0 ? -0x80000000 : -value; + } + segment[j] += value; + j++; + value = shift = 0; // reset + } + } + } + segmentify(line, segment, j); + decoded.push(line); + return decoded; + } + function segmentify(line, segment, j) { + // This looks ugly, but we're creating specialized arrays with a specific + // length. This is much faster than creating a new array (which v8 expands to + // a capacity of 17 after pushing the first item), or slicing out a subarray + // (which is slow). Length 4 is assumed to be the most frequent, followed by + // length 5 (since not everything will have an associated name), followed by + // length 1 (it's probably rare for a source substring to not have an + // associated segment data). + if (j === 4) + line.push([segment[0], segment[1], segment[2], segment[3]]); + else if (j === 5) + line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]); + else if (j === 1) + line.push([segment[0]]); + } + function encode(decoded) { + var sourceFileIndex = 0; // second field + var sourceCodeLine = 0; // third field + var sourceCodeColumn = 0; // fourth field + var nameIndex = 0; // fifth field + var mappings = ''; + for (var i = 0; i < decoded.length; i++) { + var line = decoded[i]; + if (i > 0) + mappings += ';'; + if (line.length === 0) + continue; + var generatedCodeColumn = 0; // first field + var lineMappings = []; + for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { + var segment = line_1[_i]; + var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn); + generatedCodeColumn = segment[0]; + if (segment.length > 1) { + segmentMappings += + encodeInteger(segment[1] - sourceFileIndex) + + encodeInteger(segment[2] - sourceCodeLine) + + encodeInteger(segment[3] - sourceCodeColumn); + sourceFileIndex = segment[1]; + sourceCodeLine = segment[2]; + sourceCodeColumn = segment[3]; + } + if (segment.length === 5) { + segmentMappings += encodeInteger(segment[4] - nameIndex); + nameIndex = segment[4]; + } + lineMappings.push(segmentMappings); + } + mappings += lineMappings.join(','); + } + return mappings; + } + function encodeInteger(num) { + var result = ''; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + var clamped = num & 31; + num >>>= 5; + if (num > 0) { + clamped |= 32; + } + result += chars[clamped]; + } while (num > 0); + return result; + } + + exports.decode = decode; + exports.encode = encode; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..6ea33e0 --- /dev/null +++ b/node_modules/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\t| [number]\n\t| [number, number, number, number]\n\t| [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst charToInteger: { [charCode: number]: number } = {};\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfor (let i = 0; i < chars.length; i++) {\n\tcharToInteger[chars.charCodeAt(i)] = i;\n}\n\nexport function decode(mappings: string): SourceMapMappings {\n\tconst decoded: SourceMapMappings = [];\n\tlet line: SourceMapLine = [];\n\tconst segment: SourceMapSegment = [\n\t\t0, // generated code column\n\t\t0, // source file index\n\t\t0, // source code line\n\t\t0, // source code column\n\t\t0, // name index\n\t];\n\n\tlet j = 0;\n\tfor (let i = 0, shift = 0, value = 0; i < mappings.length; i++) {\n\t\tconst c = mappings.charCodeAt(i);\n\n\t\tif (c === 44) { // \",\"\n\t\t\tsegmentify(line, segment, j);\n\t\t\tj = 0;\n\n\t\t} else if (c === 59) { // \";\"\n\t\t\tsegmentify(line, segment, j);\n\t\t\tj = 0;\n\t\t\tdecoded.push(line);\n\t\t\tline = [];\n\t\t\tsegment[0] = 0;\n\n\t\t} else {\n\t\t\tlet integer = charToInteger[c];\n\t\t\tif (integer === undefined) {\n\t\t\t\tthrow new Error('Invalid character (' + String.fromCharCode(c) + ')');\n\t\t\t}\n\n\t\t\tconst hasContinuationBit = integer & 32;\n\n\t\t\tinteger &= 31;\n\t\t\tvalue += integer << shift;\n\n\t\t\tif (hasContinuationBit) {\n\t\t\t\tshift += 5;\n\t\t\t} else {\n\t\t\t\tconst shouldNegate = value & 1;\n\t\t\t\tvalue >>>= 1;\n\n\t\t\t\tif (shouldNegate) {\n\t\t\t\t\tvalue = value === 0 ? -0x80000000 : -value;\n\t\t\t\t}\n\n\t\t\t\tsegment[j] += value;\n\t\t\t\tj++;\n\t\t\t\tvalue = shift = 0; // reset\n\t\t\t}\n\t\t}\n\t}\n\n\tsegmentify(line, segment, j);\n\tdecoded.push(line);\n\n\treturn decoded;\n}\n\nfunction segmentify(line: SourceMapSegment[], segment: SourceMapSegment, j: number) {\n\t// This looks ugly, but we're creating specialized arrays with a specific\n\t// length. This is much faster than creating a new array (which v8 expands to\n\t// a capacity of 17 after pushing the first item), or slicing out a subarray\n\t// (which is slow). Length 4 is assumed to be the most frequent, followed by\n\t// length 5 (since not everything will have an associated name), followed by\n\t// length 1 (it's probably rare for a source substring to not have an\n\t// associated segment data).\n\tif (j === 4) line.push([segment[0], segment[1], segment[2], segment[3]]);\n\telse if (j === 5) line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);\n\telse if (j === 1) line.push([segment[0]]);\n}\n\nexport function encode(decoded: SourceMapMappings): string {\n\tlet sourceFileIndex = 0; // second field\n\tlet sourceCodeLine = 0; // third field\n\tlet sourceCodeColumn = 0; // fourth field\n\tlet nameIndex = 0; // fifth field\n\tlet mappings = '';\n\n\tfor (let i = 0; i < decoded.length; i++) {\n\t\tconst line = decoded[i];\n\t\tif (i > 0) mappings += ';';\n\t\tif (line.length === 0) continue;\n\n\t\tlet generatedCodeColumn = 0; // first field\n\n\t\tconst lineMappings: string[] = [];\n\n\t\tfor (const segment of line) {\n\t\t\tlet segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);\n\t\t\tgeneratedCodeColumn = segment[0];\n\n\t\t\tif (segment.length > 1) {\n\t\t\t\tsegmentMappings +=\n\t\t\t\t\tencodeInteger(segment[1] - sourceFileIndex) +\n\t\t\t\t\tencodeInteger(segment[2] - sourceCodeLine) +\n\t\t\t\t\tencodeInteger(segment[3] - sourceCodeColumn);\n\n\t\t\t\tsourceFileIndex = segment[1];\n\t\t\t\tsourceCodeLine = segment[2];\n\t\t\t\tsourceCodeColumn = segment[3];\n\t\t\t}\n\n\t\t\tif (segment.length === 5) {\n\t\t\t\tsegmentMappings += encodeInteger(segment[4] - nameIndex);\n\t\t\t\tnameIndex = segment[4];\n\t\t\t}\n\n\t\t\tlineMappings.push(segmentMappings);\n\t\t}\n\n\t\tmappings += lineMappings.join(',');\n\t}\n\n\treturn mappings;\n}\n\nfunction encodeInteger(num: number): string {\n\tvar result = '';\n\tnum = num < 0 ? (-num << 1) | 1 : num << 1;\n\tdo {\n\t\tvar clamped = num & 31;\n\t\tnum >>>= 5;\n\t\tif (num > 0) {\n\t\t\tclamped |= 32;\n\t\t}\n\t\tresult += chars[clamped];\n\t} while (num > 0);\n\n\treturn result;\n}\n"],"names":[],"mappings":";;;;;;CAOA,IAAM,aAAa,GAAmC,EAAE,CAAC;CACzD,IAAM,KAAK,GAAG,mEAAmE,CAAC;CAElF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;KACtC,aAAa,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;EACvC;AAED,UAAgB,MAAM,CAAC,QAAgB;KACtC,IAAM,OAAO,GAAsB,EAAE,CAAC;KACtC,IAAI,IAAI,GAAkB,EAAE,CAAC;KAC7B,IAAM,OAAO,GAAqB;SACjC,CAAC;SACD,CAAC;SACD,CAAC;SACD,CAAC;SACD,CAAC;MACD,CAAC;KAEF,IAAI,CAAC,GAAG,CAAC,CAAC;KACV,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;SAC/D,IAAM,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;SAEjC,IAAI,CAAC,KAAK,EAAE,EAAE;aACb,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;aAC7B,CAAC,GAAG,CAAC,CAAC;UAEN;cAAM,IAAI,CAAC,KAAK,EAAE,EAAE;aACpB,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;aAC7B,CAAC,GAAG,CAAC,CAAC;aACN,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aACnB,IAAI,GAAG,EAAE,CAAC;aACV,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;UAEf;cAAM;aACN,IAAI,OAAO,GAAG,aAAa,CAAC,CAAC,CAAC,CAAC;aAC/B,IAAI,OAAO,KAAK,SAAS,EAAE;iBAC1B,MAAM,IAAI,KAAK,CAAC,qBAAqB,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC;cACtE;aAED,IAAM,kBAAkB,GAAG,OAAO,GAAG,EAAE,CAAC;aAExC,OAAO,IAAI,EAAE,CAAC;aACd,KAAK,IAAI,OAAO,IAAI,KAAK,CAAC;aAE1B,IAAI,kBAAkB,EAAE;iBACvB,KAAK,IAAI,CAAC,CAAC;cACX;kBAAM;iBACN,IAAM,YAAY,GAAG,KAAK,GAAG,CAAC,CAAC;iBAC/B,KAAK,MAAM,CAAC,CAAC;iBAEb,IAAI,YAAY,EAAE;qBACjB,KAAK,GAAG,KAAK,KAAK,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,KAAK,CAAC;kBAC3C;iBAED,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC;iBACpB,CAAC,EAAE,CAAC;iBACJ,KAAK,GAAG,KAAK,GAAG,CAAC,CAAC;cAClB;UACD;MACD;KAED,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;KAC7B,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;KAEnB,OAAO,OAAO,CAAC;CAChB,CAAC;CAED,SAAS,UAAU,CAAC,IAAwB,EAAE,OAAyB,EAAE,CAAS;;;;;;;;KAQjF,IAAI,CAAC,KAAK,CAAC;SAAE,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;UACpE,IAAI,CAAC,KAAK,CAAC;SAAE,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;UACrF,IAAI,CAAC,KAAK,CAAC;SAAE,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAC3C,CAAC;AAED,UAAgB,MAAM,CAAC,OAA0B;KAChD,IAAI,eAAe,GAAG,CAAC,CAAC;KACxB,IAAI,cAAc,GAAG,CAAC,CAAC;KACvB,IAAI,gBAAgB,GAAG,CAAC,CAAC;KACzB,IAAI,SAAS,GAAG,CAAC,CAAC;KAClB,IAAI,QAAQ,GAAG,EAAE,CAAC;KAElB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;SACxC,IAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;SACxB,IAAI,CAAC,GAAG,CAAC;aAAE,QAAQ,IAAI,GAAG,CAAC;SAC3B,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;aAAE,SAAS;SAEhC,IAAI,mBAAmB,GAAG,CAAC,CAAC;SAE5B,IAAM,YAAY,GAAa,EAAE,CAAC;SAElC,KAAsB,UAAI,EAAJ,aAAI,EAAJ,kBAAI,EAAJ,IAAI,EAAE;aAAvB,IAAM,OAAO,aAAA;aACjB,IAAI,eAAe,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAAC,CAAC;aACtE,mBAAmB,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;aAEjC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;iBACvB,eAAe;qBACd,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,eAAe,CAAC;yBAC3C,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,cAAc,CAAC;yBAC1C,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAC,CAAC;iBAE9C,eAAe,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;iBAC7B,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;iBAC5B,gBAAgB,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;cAC9B;aAED,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;iBACzB,eAAe,IAAI,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;iBACzD,SAAS,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;cACvB;aAED,YAAY,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;UACnC;SAED,QAAQ,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;MACnC;KAED,OAAO,QAAQ,CAAC;CACjB,CAAC;CAED,SAAS,aAAa,CAAC,GAAW;KACjC,IAAI,MAAM,GAAG,EAAE,CAAC;KAChB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;KAC3C,GAAG;SACF,IAAI,OAAO,GAAG,GAAG,GAAG,EAAE,CAAC;SACvB,GAAG,MAAM,CAAC,CAAC;SACX,IAAI,GAAG,GAAG,CAAC,EAAE;aACZ,OAAO,IAAI,EAAE,CAAC;UACd;SACD,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;MACzB,QAAQ,GAAG,GAAG,CAAC,EAAE;KAElB,OAAO,MAAM,CAAC;CACf,CAAC;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/sourcemap-codec/dist/types/sourcemap-codec.d.ts b/node_modules/sourcemap-codec/dist/types/sourcemap-codec.d.ts new file mode 100644 index 0000000..6ac3c1d --- /dev/null +++ b/node_modules/sourcemap-codec/dist/types/sourcemap-codec.d.ts @@ -0,0 +1,5 @@ +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; diff --git a/node_modules/sourcemap-codec/package.json b/node_modules/sourcemap-codec/package.json new file mode 100644 index 0000000..4b2d219 --- /dev/null +++ b/node_modules/sourcemap-codec/package.json @@ -0,0 +1,53 @@ +{ + "name": "sourcemap-codec", + "version": "1.4.8", + "description": "Encode/decode sourcemap mappings", + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.es.js", + "types": "dist/types/sourcemap-codec.d.ts", + "scripts": { + "test": "mocha", + "build": "rm -rf dist && rollup -c && tsc", + "pretest": "npm run build", + "prepublish": "npm test", + "lint": "eslint src", + "pretest-coverage": "npm run build", + "test-coverage": "rm -rf coverage/* && istanbul cover --report json node_modules/.bin/_mocha -- -u exports -R spec test/test.js", + "posttest-coverage": "remap-istanbul -i coverage/coverage-final.json -o coverage/coverage-remapped.json -b dist && remap-istanbul -i coverage/coverage-final.json -o coverage/coverage-remapped.lcov -t lcovonly -b dist && remap-istanbul -i coverage/coverage-final.json -o coverage/coverage-remapped -t html -b dist", + "ci": "npm run test-coverage && codecov < coverage/coverage-remapped.lcov" + }, + "repository": { + "type": "git", + "url": "https://github.com/Rich-Harris/sourcemap-codec" + }, + "keywords": [ + "sourcemap", + "vlq" + ], + "author": "Rich Harris", + "license": "MIT", + "bugs": { + "url": "https://github.com/Rich-Harris/sourcemap-codec/issues" + }, + "homepage": "https://github.com/Rich-Harris/sourcemap-codec", + "dependencies": {}, + "devDependencies": { + "codecov.io": "^0.1.6", + "console-group": "^0.3.3", + "eslint": "^6.0.1", + "eslint-plugin-import": "^2.18.0", + "istanbul": "^0.4.5", + "mocha": "^6.1.4", + "remap-istanbul": "^0.13.0", + "rollup": "^1.16.4", + "rollup-plugin-node-resolve": "^5.2.0", + "rollup-plugin-typescript": "^1.0.1", + "typescript": "^3.5.2" + }, + "files": [ + "dist/*.js", + "dist/*.js.map", + "dist/**/*.d.ts", + "README.md" + ] +} diff --git a/node_modules/stack-utils/LICENSE.md b/node_modules/stack-utils/LICENSE.md new file mode 100644 index 0000000..97df981 --- /dev/null +++ b/node_modules/stack-utils/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016-2022 Isaac Z. Schlueter , James Talmage (github.com/jamestalmage), 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/stack-utils/index.js b/node_modules/stack-utils/index.js new file mode 100644 index 0000000..f567133 --- /dev/null +++ b/node_modules/stack-utils/index.js @@ -0,0 +1,344 @@ +'use strict'; + +const escapeStringRegexp = require('escape-string-regexp'); + +const cwd = typeof process === 'object' && process && typeof process.cwd === 'function' + ? process.cwd() + : '.' + +const natives = [].concat( + require('module').builtinModules, + 'bootstrap_node', + 'node', +).map(n => new RegExp(`(?:\\((?:node:)?${n}(?:\\.js)?:\\d+:\\d+\\)$|^\\s*at (?:node:)?${n}(?:\\.js)?:\\d+:\\d+$)`)); + +natives.push( + /\((?:node:)?internal\/[^:]+:\d+:\d+\)$/, + /\s*at (?:node:)?internal\/[^:]+:\d+:\d+$/, + /\/\.node-spawn-wrap-\w+-\w+\/node:\d+:\d+\)?$/ +); + +class StackUtils { + constructor (opts) { + opts = { + ignoredPackages: [], + ...opts + }; + + if ('internals' in opts === false) { + opts.internals = StackUtils.nodeInternals(); + } + + if ('cwd' in opts === false) { + opts.cwd = cwd + } + + this._cwd = opts.cwd.replace(/\\/g, '/'); + this._internals = [].concat( + opts.internals, + ignoredPackagesRegExp(opts.ignoredPackages) + ); + + this._wrapCallSite = opts.wrapCallSite || false; + } + + static nodeInternals () { + return [...natives]; + } + + clean (stack, indent = 0) { + indent = ' '.repeat(indent); + + if (!Array.isArray(stack)) { + stack = stack.split('\n'); + } + + if (!(/^\s*at /.test(stack[0])) && (/^\s*at /.test(stack[1]))) { + stack = stack.slice(1); + } + + let outdent = false; + let lastNonAtLine = null; + const result = []; + + stack.forEach(st => { + st = st.replace(/\\/g, '/'); + + if (this._internals.some(internal => internal.test(st))) { + return; + } + + const isAtLine = /^\s*at /.test(st); + + if (outdent) { + st = st.trimEnd().replace(/^(\s+)at /, '$1'); + } else { + st = st.trim(); + if (isAtLine) { + st = st.slice(3); + } + } + + st = st.replace(`${this._cwd}/`, ''); + + if (st) { + if (isAtLine) { + if (lastNonAtLine) { + result.push(lastNonAtLine); + lastNonAtLine = null; + } + + result.push(st); + } else { + outdent = true; + lastNonAtLine = st; + } + } + }); + + return result.map(line => `${indent}${line}\n`).join(''); + } + + captureString (limit, fn = this.captureString) { + if (typeof limit === 'function') { + fn = limit; + limit = Infinity; + } + + const {stackTraceLimit} = Error; + if (limit) { + Error.stackTraceLimit = limit; + } + + const obj = {}; + + Error.captureStackTrace(obj, fn); + const {stack} = obj; + Error.stackTraceLimit = stackTraceLimit; + + return this.clean(stack); + } + + capture (limit, fn = this.capture) { + if (typeof limit === 'function') { + fn = limit; + limit = Infinity; + } + + const {prepareStackTrace, stackTraceLimit} = Error; + Error.prepareStackTrace = (obj, site) => { + if (this._wrapCallSite) { + return site.map(this._wrapCallSite); + } + + return site; + }; + + if (limit) { + Error.stackTraceLimit = limit; + } + + const obj = {}; + Error.captureStackTrace(obj, fn); + const { stack } = obj; + Object.assign(Error, {prepareStackTrace, stackTraceLimit}); + + return stack; + } + + at (fn = this.at) { + const [site] = this.capture(1, fn); + + if (!site) { + return {}; + } + + const res = { + line: site.getLineNumber(), + column: site.getColumnNumber() + }; + + setFile(res, site.getFileName(), this._cwd); + + if (site.isConstructor()) { + Object.defineProperty(res, 'constructor', { + value: true, + configurable: true, + }); + } + + if (site.isEval()) { + res.evalOrigin = site.getEvalOrigin(); + } + + // Node v10 stopped with the isNative() on callsites, apparently + /* istanbul ignore next */ + if (site.isNative()) { + res.native = true; + } + + let typename; + try { + typename = site.getTypeName(); + } catch (_) { + } + + if (typename && typename !== 'Object' && typename !== '[object Object]') { + res.type = typename; + } + + const fname = site.getFunctionName(); + if (fname) { + res.function = fname; + } + + const meth = site.getMethodName(); + if (meth && fname !== meth) { + res.method = meth; + } + + return res; + } + + parseLine (line) { + const match = line && line.match(re); + if (!match) { + return null; + } + + const ctor = match[1] === 'new'; + let fname = match[2]; + const evalOrigin = match[3]; + const evalFile = match[4]; + const evalLine = Number(match[5]); + const evalCol = Number(match[6]); + let file = match[7]; + const lnum = match[8]; + const col = match[9]; + const native = match[10] === 'native'; + const closeParen = match[11] === ')'; + let method; + + const res = {}; + + if (lnum) { + res.line = Number(lnum); + } + + if (col) { + res.column = Number(col); + } + + if (closeParen && file) { + // make sure parens are balanced + // if we have a file like "asdf) [as foo] (xyz.js", then odds are + // that the fname should be += " (asdf) [as foo]" and the file + // should be just "xyz.js" + // walk backwards from the end to find the last unbalanced ( + let closes = 0; + for (let i = file.length - 1; i > 0; i--) { + if (file.charAt(i) === ')') { + closes++; + } else if (file.charAt(i) === '(' && file.charAt(i - 1) === ' ') { + closes--; + if (closes === -1 && file.charAt(i - 1) === ' ') { + const before = file.slice(0, i - 1); + const after = file.slice(i + 1); + file = after; + fname += ` (${before}`; + break; + } + } + } + } + + if (fname) { + const methodMatch = fname.match(methodRe); + if (methodMatch) { + fname = methodMatch[1]; + method = methodMatch[2]; + } + } + + setFile(res, file, this._cwd); + + if (ctor) { + Object.defineProperty(res, 'constructor', { + value: true, + configurable: true, + }); + } + + if (evalOrigin) { + res.evalOrigin = evalOrigin; + res.evalLine = evalLine; + res.evalColumn = evalCol; + res.evalFile = evalFile && evalFile.replace(/\\/g, '/'); + } + + if (native) { + res.native = true; + } + + if (fname) { + res.function = fname; + } + + if (method && fname !== method) { + res.method = method; + } + + return res; + } +} + +function setFile (result, filename, cwd) { + if (filename) { + filename = filename.replace(/\\/g, '/'); + if (filename.startsWith(`${cwd}/`)) { + filename = filename.slice(cwd.length + 1); + } + + result.file = filename; + } +} + +function ignoredPackagesRegExp(ignoredPackages) { + if (ignoredPackages.length === 0) { + return []; + } + + const packages = ignoredPackages.map(mod => escapeStringRegexp(mod)); + + return new RegExp(`[\/\\\\]node_modules[\/\\\\](?:${packages.join('|')})[\/\\\\][^:]+:\\d+:\\d+`) +} + +const re = new RegExp( + '^' + + // Sometimes we strip out the ' at' because it's noisy + '(?:\\s*at )?' + + // $1 = ctor if 'new' + '(?:(new) )?' + + // $2 = function name (can be literally anything) + // May contain method at the end as [as xyz] + '(?:(.*?) \\()?' + + // (eval at (file.js:1:1), + // $3 = eval origin + // $4:$5:$6 are eval file/line/col, but not normally reported + '(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?' + + // file:line:col + // $7:$8:$9 + // $10 = 'native' if native + '(?:(.+?):(\\d+):(\\d+)|(native))' + + // maybe close the paren, then end + // if $11 is ), then we only allow balanced parens in the filename + // any imbalance is placed on the fname. This is a heuristic, and + // bound to be incorrect in some edge cases. The bet is that + // having weird characters in method names is more common than + // having weird characters in filenames, which seems reasonable. + '(\\)?)$' +); + +const methodRe = /^(.*?) \[as (.*?)\]$/; + +module.exports = StackUtils; diff --git a/node_modules/stack-utils/package.json b/node_modules/stack-utils/package.json new file mode 100644 index 0000000..00acfa3 --- /dev/null +++ b/node_modules/stack-utils/package.json @@ -0,0 +1,39 @@ +{ + "name": "stack-utils", + "version": "2.0.6", + "description": "Captures and cleans stack traces", + "license": "MIT", + "repository": "tapjs/stack-utils", + "author": { + "name": "James Talmage", + "email": "james@talmage.io", + "url": "github.com/jamestalmage" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags" + }, + "tap": { + "check-coverage": true + }, + "files": [ + "index.js" + ], + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "devDependencies": { + "bluebird": "^3.7.2", + "coveralls": "^3.0.9", + "nested-error-stacks": "^2.1.0", + "pify": "^4.0.1", + "q": "^1.5.1", + "source-map-support": "^0.5.20", + "tap": "^16.3.0" + } +} diff --git a/node_modules/stack-utils/readme.md b/node_modules/stack-utils/readme.md new file mode 100644 index 0000000..c91f9d0 --- /dev/null +++ b/node_modules/stack-utils/readme.md @@ -0,0 +1,143 @@ +# stack-utils + +> Captures and cleans stack traces. + +[![Linux Build](https://travis-ci.org/tapjs/stack-utils.svg?branch=master)](https://travis-ci.org/tapjs/stack-utils) [![Build status](https://ci.appveyor.com/api/projects/status/fb9i157knoixe3iq/branch/master?svg=true)](https://ci.appveyor.com/project/jamestalmage/stack-utils-oiw96/branch/master) [![Coverage](https://coveralls.io/repos/tapjs/stack-utils/badge.svg?branch=master&service=github)](https://coveralls.io/github/tapjs/stack-utils?branch=master) + + +Extracted from `lib/stack.js` in the [`node-tap` project](https://github.com/tapjs/node-tap) + +## Install + +``` +$ npm install --save stack-utils +``` + + +## Usage + +```js +const StackUtils = require('stack-utils'); +const stack = new StackUtils({cwd: process.cwd(), internals: StackUtils.nodeInternals()}); + +console.log(stack.clean(new Error().stack)); +// outputs a beautified stack trace +``` + + +## API + + +### new StackUtils([options]) + +Creates a new `stackUtils` instance. + +#### options + +##### internals + +Type: `array` of `RegularExpression`s + +A set of regular expressions that match internal stack stack trace lines which should be culled from the stack trace. +The default is `StackUtils.nodeInternals()`, this can be disabled by setting `[]` or appended using +`StackUtils.nodeInternals().concat(additionalRegExp)`. See also `ignoredPackages`. + +##### ignoredPackages + +Type: `array` of `string`s + +An array of npm modules to be culled from the stack trace. This list will mapped to regular +expressions and merged with the `internals`. + +Default `''`. + +##### cwd + +Type: `string` + +The path to the current working directory. File names in the stack trace will be shown relative to this directory. + +##### wrapCallSite + +Type: `function(CallSite)` + +A mapping function for manipulating CallSites before processing. The first argument is a CallSite instance, and the function should return a modified CallSite. This is useful for providing source map support. + + +### StackUtils.nodeInternals() + +Returns an array of regular expressions that be used to cull lines from the stack trace that reference common Node.js internal files. + + +### stackUtils.clean(stack, indent = 0) + +Cleans up a stack trace by deleting any lines that match the `internals` passed to the constructor, and shortening file names relative to `cwd`. + +Returns a `string` with the cleaned up stack (always terminated with a `\n` newline character). +Spaces at the start of each line are trimmed, indentation can be added by setting `indent` to the desired number of spaces. + +#### stack + +*Required* +Type: `string` or an `array` of `string`s + + +### stackUtils.capture([limit], [startStackFunction]) + +Captures the current stack trace, returning an array of `CallSite`s. There are good overviews of the available CallSite methods [here](https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces), and [here](https://github.com/sindresorhus/callsites#api). + +#### limit + +Type: `number` +Default: `Infinity` + +Limits the number of lines returned by dropping all lines in excess of the limit. This removes lines from the stack trace. + +#### startStackFunction + +Type: `function` + +The function where the stack trace should start. The first line of the stack trace will be the function that called `startStackFunction`. This removes lines from the end of the stack trace. + + +### stackUtils.captureString([limit], [startStackFunction]) + +Captures the current stack trace, cleans it using `stackUtils.clean(stack)`, and returns a string with the cleaned stack trace. It takes the same arguments as `stackUtils.capture`. + + +### stackUtils.at([startStackFunction]) + +Captures the first line of the stack trace (or the first line after `startStackFunction` if supplied), and returns a `CallSite` like object that is serialization friendly (properties are actual values instead of getter functions). + +The available properties are: + + - `line`: `number` + - `column`: `number` + - `file`: `string` + - `constructor`: `boolean` + - `evalOrigin`: `string` + - `native`: `boolean` + - `type`: `string` + - `function`: `string` + - `method`: `string` + +### stackUtils.parseLine(line) + +Parses a `string` (which should be a single line from a stack trace), and generates an object with the following properties: + + - `line`: `number` + - `column`: `number` + - `file`: `string` + - `constructor`: `boolean` + - `evalOrigin`: `string` + - `evalLine`: `number` + - `evalColumn`: `number` + - `evalFile`: `string` + - `native`: `boolean` + - `function`: `string` + - `method`: `string` + + +## License + +MIT © [Isaac Z. Schlueter](http://github.com/isaacs), [James Talmage](http://github.com/jamestalmage) diff --git a/node_modules/strip-final-newline/index.js b/node_modules/strip-final-newline/index.js new file mode 100644 index 0000000..78fc0c5 --- /dev/null +++ b/node_modules/strip-final-newline/index.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = input => { + const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); + const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); + + if (input[input.length - 1] === LF) { + input = input.slice(0, input.length - 1); + } + + if (input[input.length - 1] === CR) { + input = input.slice(0, input.length - 1); + } + + return input; +}; diff --git a/node_modules/strip-final-newline/license b/node_modules/strip-final-newline/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/strip-final-newline/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/strip-final-newline/package.json b/node_modules/strip-final-newline/package.json new file mode 100644 index 0000000..d9f2a6c --- /dev/null +++ b/node_modules/strip-final-newline/package.json @@ -0,0 +1,40 @@ +{ + "name": "strip-final-newline", + "version": "2.0.0", + "description": "Strip the final newline character from a string/buffer", + "license": "MIT", + "repository": "sindresorhus/strip-final-newline", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "strip", + "trim", + "remove", + "delete", + "final", + "last", + "end", + "file", + "newline", + "linebreak", + "character", + "string", + "buffer" + ], + "devDependencies": { + "ava": "^0.25.0", + "xo": "^0.23.0" + } +} diff --git a/node_modules/strip-final-newline/readme.md b/node_modules/strip-final-newline/readme.md new file mode 100644 index 0000000..32dfd50 --- /dev/null +++ b/node_modules/strip-final-newline/readme.md @@ -0,0 +1,30 @@ +# strip-final-newline [![Build Status](https://travis-ci.com/sindresorhus/strip-final-newline.svg?branch=master)](https://travis-ci.com/sindresorhus/strip-final-newline) + +> Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from a string/buffer + +Can be useful when parsing the output of, for example, `ChildProcess#execFile`, as [binaries usually output a newline at the end](https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline). Normally, you would use `stdout.trim()`, but that would also remove newlines at the start and whitespace. + + +## Install + +``` +$ npm install strip-final-newline +``` + + +## Usage + +```js +const stripFinalNewline = require('strip-final-newline'); + +stripFinalNewline('foo\nbar\n\n'); +//=> 'foo\nbar\n' + +stripFinalNewline(Buffer.from('foo\nbar\n\n')).toString(); +//=> 'foo\nbar\n' +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/strip-indent/index.d.ts b/node_modules/strip-indent/index.d.ts new file mode 100644 index 0000000..44f2304 --- /dev/null +++ b/node_modules/strip-indent/index.d.ts @@ -0,0 +1,21 @@ +/** +Strip leading whitespace from each line in a string. + +The line with the least number of leading whitespace, ignoring empty lines, determines the number to remove. + +@example +``` +import stripIndent = require('strip-indent'); + +const string = '\tunicorn\n\t\tcake'; +// unicorn +// cake + +stripIndent(string); +//unicorn +// cake +``` +*/ +declare function stripIndent(string: string): string; + +export = stripIndent; diff --git a/node_modules/strip-indent/index.js b/node_modules/strip-indent/index.js new file mode 100644 index 0000000..7ba3b15 --- /dev/null +++ b/node_modules/strip-indent/index.js @@ -0,0 +1,14 @@ +'use strict'; +const minIndent = require('min-indent'); + +module.exports = string => { + const indent = minIndent(string); + + if (indent === 0) { + return string; + } + + const regex = new RegExp(`^[ \\t]{${indent}}`, 'gm'); + + return string.replace(regex, ''); +}; diff --git a/node_modules/strip-indent/license b/node_modules/strip-indent/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/strip-indent/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/strip-indent/package.json b/node_modules/strip-indent/package.json new file mode 100644 index 0000000..d66a003 --- /dev/null +++ b/node_modules/strip-indent/package.json @@ -0,0 +1,42 @@ +{ + "name": "strip-indent", + "version": "3.0.0", + "description": "Strip leading whitespace from each line in a string", + "license": "MIT", + "repository": "sindresorhus/strip-indent", + "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": [ + "strip", + "indent", + "indentation", + "normalize", + "remove", + "delete", + "whitespace", + "space", + "tab", + "string" + ], + "dependencies": { + "min-indent": "^1.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/strip-indent/readme.md b/node_modules/strip-indent/readme.md new file mode 100644 index 0000000..f14f6ba --- /dev/null +++ b/node_modules/strip-indent/readme.md @@ -0,0 +1,44 @@ +# strip-indent [![Build Status](https://travis-ci.org/sindresorhus/strip-indent.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-indent) + +> Strip leading whitespace from each line in a string + +The line with the least number of leading whitespace, ignoring empty lines, determines the number to remove. + +Useful for removing redundant indentation. + + +## Install + +``` +$ npm install strip-indent +``` + + +## Usage + +```js +const stripIndent = require('strip-indent'); + +const string = '\tunicorn\n\t\tcake'; +/* + unicorn + cake +*/ + +stripIndent(string); +/* +unicorn + cake +*/ +``` + + +## Related + +- [strip-indent-cli](https://github.com/sindresorhus/strip-indent-cli) - CLI for this module +- [indent-string](https://github.com/sindresorhus/indent-string) - Indent each line in a string + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/strip-literal/LICENSE b/node_modules/strip-literal/LICENSE new file mode 100644 index 0000000..7d71216 --- /dev/null +++ b/node_modules/strip-literal/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Anthony Fu + +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/strip-literal/README.md b/node_modules/strip-literal/README.md new file mode 100644 index 0000000..b2b2208 --- /dev/null +++ b/node_modules/strip-literal/README.md @@ -0,0 +1,62 @@ +# strip-literal + +[![NPM version](https://img.shields.io/npm/v/strip-literal?color=a1b858&label=)](https://www.npmjs.com/package/strip-literal) + +Strip comments and string literals from JavaScript code. Powered by [acorn](https://github.com/acornjs/acorn)'s tokenizer. + +## Usage + + + +```ts +import { stripLiteral } from 'strip-literal' + +stripLiteral('const foo = `//foo ${bar}`') // 'const foo = ` ${bar}`' +``` + +Comments, string literals will be replaced by spaces with the same length to keep the source map untouched. + +## Functions + +### `stripLiteralAcorn` + +Strip literal using [Acorn](https://github.com/acornjs/acorn)'s tokenizer. + +Will throw error if the input is not valid JavaScript. + +[Source](./src/acorn.ts) + +### `stripLiteralRegex` + +Strip literal using RegExp. + +This will be faster and can work on non-JavaScript input. But will have some caveats on distinguish strings and comments. + +[Source](./src/regex.ts) + +### `stripLiteral` + +Strip literal from code. + +Try to use `stripLiteralAcorn` first, and fallback to `stripLiteralRegex` if Acorn fails. + +[Source](./src/index.ts) + +### `createIsLiteralPositionAcorn` +Returns a function that returns whether the position is in a literal using [Acorn](https://github.com/acornjs/acorn)'s tokenizer. + +Will throw error if the input is not valid JavaScript. + +[Source](./src/acorn.ts) + +## Sponsors + +

+ + + +

+ +## License + +[MIT](./LICENSE) License © 2022 [Anthony Fu](https://github.com/antfu) diff --git a/node_modules/strip-literal/dist/index.cjs b/node_modules/strip-literal/dist/index.cjs new file mode 100644 index 0000000..2ce1713 --- /dev/null +++ b/node_modules/strip-literal/dist/index.cjs @@ -0,0 +1,115 @@ +'use strict'; + +const acorn = require('acorn'); + +function stripLiteralAcorn(code) { + const FILL = " "; + let result = ""; + function fulfill(index) { + if (index > result.length) + result += code.slice(result.length, index).replace(/[^\n]/g, FILL); + } + const tokens = acorn.tokenizer(code, { + ecmaVersion: "latest", + sourceType: "module", + allowHashBang: true, + allowAwaitOutsideFunction: true, + allowImportExportEverywhere: true + }); + const inter = tokens[Symbol.iterator](); + while (true) { + const { done, value: token } = inter.next(); + if (done) + break; + fulfill(token.start); + if (token.type.label === "string") + result += code[token.start] + FILL.repeat(token.end - token.start - 2) + code[token.end - 1]; + else if (token.type.label === "template") + result += FILL.repeat(token.end - token.start); + else + result += code.slice(token.start, token.end); + } + fulfill(code.length); + return result; +} +function createIsLiteralPositionAcorn(code) { + const positionList = []; + const tokens = acorn.tokenizer(code, { + ecmaVersion: "latest", + sourceType: "module", + allowHashBang: true, + allowAwaitOutsideFunction: true, + allowImportExportEverywhere: true, + onComment(_isBlock, _text, start, end) { + positionList.push(start); + positionList.push(end); + } + }); + const inter = tokens[Symbol.iterator](); + while (true) { + const { done, value: token } = inter.next(); + if (done) + break; + if (token.type.label === "string") { + positionList.push(token.start + 1); + positionList.push(token.end - 1); + } else if (token.type.label === "template") { + positionList.push(token.start); + positionList.push(token.end); + } + } + return (position) => { + const i = binarySearch(positionList, (v) => position < v); + return (i - 1) % 2 === 0; + }; +} +function binarySearch(array, pred) { + let low = -1; + let high = array.length; + while (1 + low < high) { + const mid = low + (high - low >> 1); + if (pred(array[mid])) + high = mid; + else + low = mid; + } + return high; +} + +const multilineCommentsRE = /\/\*.*?\*\//gms; +const singlelineCommentsRE = /(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/gm; +const templateLiteralRE = /\$\{(\s*(?:(?!\$\{).|\n|\r)*?\s*)\}/g; +const quotesRE = [ + /(["'`])((?:\\\1|(?!\1)|.|\r)*?)\1/gm, + /([`])((?:\\\1|(?!\1)|.|\n|\r)*?)\1/gm +]; +function stripLiteralRegex(code) { + code = code.replace(multilineCommentsRE, (s) => " ".repeat(s.length)).replace(singlelineCommentsRE, (s) => " ".repeat(s.length)); + let expanded = code; + for (let i = 0; i < 16; i++) { + const before = expanded; + expanded = expanded.replace(templateLiteralRE, "` $1`"); + if (expanded === before) + break; + } + quotesRE.forEach((re) => { + expanded = expanded.replace(re, (s, quote, body, index) => { + code = code.slice(0, index + 1) + " ".repeat(s.length - 2) + code.slice(index + s.length - 1); + return quote + " ".repeat(s.length - 2) + quote; + }); + }); + return code; +} + +function stripLiteral(code) { + try { + return stripLiteralAcorn(code); + } catch (e) { + return stripLiteralRegex(code); + } +} + +exports.createIsLiteralPositionAcorn = createIsLiteralPositionAcorn; +exports.stripLiteral = stripLiteral; +exports.stripLiteralAcorn = stripLiteralAcorn; +exports.stripLiteralRegex = stripLiteralRegex; diff --git a/node_modules/strip-literal/dist/index.d.ts b/node_modules/strip-literal/dist/index.d.ts new file mode 100644 index 0000000..a96e412 --- /dev/null +++ b/node_modules/strip-literal/dist/index.d.ts @@ -0,0 +1,30 @@ +/** + * Strip literal using Acorn's tokenizer. + * + * Will throw error if the input is not valid JavaScript. + */ +declare function stripLiteralAcorn(code: string): string; +/** + * Returns a function that returns whether the position is + * in a literal using Acorn's tokenizer. + * + * Will throw error if the input is not valid JavaScript. + */ +declare function createIsLiteralPositionAcorn(code: string): (position: number) => boolean; + +/** + * Strip literal using RegExp. + * + * This will be faster and can work on non-JavaScript input. + * But will have some caveats on distinguish strings and comments. + */ +declare function stripLiteralRegex(code: string): string; + +/** + * Strip literal from code. + * + * Using Acorn's tokenizer first, and fallback to Regex if Acorn fails. + */ +declare function stripLiteral(code: string): string; + +export { createIsLiteralPositionAcorn, stripLiteral, stripLiteralAcorn, stripLiteralRegex }; diff --git a/node_modules/strip-literal/dist/index.mjs b/node_modules/strip-literal/dist/index.mjs new file mode 100644 index 0000000..eaa94e0 --- /dev/null +++ b/node_modules/strip-literal/dist/index.mjs @@ -0,0 +1,110 @@ +import { tokenizer } from 'acorn'; + +function stripLiteralAcorn(code) { + const FILL = " "; + let result = ""; + function fulfill(index) { + if (index > result.length) + result += code.slice(result.length, index).replace(/[^\n]/g, FILL); + } + const tokens = tokenizer(code, { + ecmaVersion: "latest", + sourceType: "module", + allowHashBang: true, + allowAwaitOutsideFunction: true, + allowImportExportEverywhere: true + }); + const inter = tokens[Symbol.iterator](); + while (true) { + const { done, value: token } = inter.next(); + if (done) + break; + fulfill(token.start); + if (token.type.label === "string") + result += code[token.start] + FILL.repeat(token.end - token.start - 2) + code[token.end - 1]; + else if (token.type.label === "template") + result += FILL.repeat(token.end - token.start); + else + result += code.slice(token.start, token.end); + } + fulfill(code.length); + return result; +} +function createIsLiteralPositionAcorn(code) { + const positionList = []; + const tokens = tokenizer(code, { + ecmaVersion: "latest", + sourceType: "module", + allowHashBang: true, + allowAwaitOutsideFunction: true, + allowImportExportEverywhere: true, + onComment(_isBlock, _text, start, end) { + positionList.push(start); + positionList.push(end); + } + }); + const inter = tokens[Symbol.iterator](); + while (true) { + const { done, value: token } = inter.next(); + if (done) + break; + if (token.type.label === "string") { + positionList.push(token.start + 1); + positionList.push(token.end - 1); + } else if (token.type.label === "template") { + positionList.push(token.start); + positionList.push(token.end); + } + } + return (position) => { + const i = binarySearch(positionList, (v) => position < v); + return (i - 1) % 2 === 0; + }; +} +function binarySearch(array, pred) { + let low = -1; + let high = array.length; + while (1 + low < high) { + const mid = low + (high - low >> 1); + if (pred(array[mid])) + high = mid; + else + low = mid; + } + return high; +} + +const multilineCommentsRE = /\/\*.*?\*\//gms; +const singlelineCommentsRE = /(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/gm; +const templateLiteralRE = /\$\{(\s*(?:(?!\$\{).|\n|\r)*?\s*)\}/g; +const quotesRE = [ + /(["'`])((?:\\\1|(?!\1)|.|\r)*?)\1/gm, + /([`])((?:\\\1|(?!\1)|.|\n|\r)*?)\1/gm +]; +function stripLiteralRegex(code) { + code = code.replace(multilineCommentsRE, (s) => " ".repeat(s.length)).replace(singlelineCommentsRE, (s) => " ".repeat(s.length)); + let expanded = code; + for (let i = 0; i < 16; i++) { + const before = expanded; + expanded = expanded.replace(templateLiteralRE, "` $1`"); + if (expanded === before) + break; + } + quotesRE.forEach((re) => { + expanded = expanded.replace(re, (s, quote, body, index) => { + code = code.slice(0, index + 1) + " ".repeat(s.length - 2) + code.slice(index + s.length - 1); + return quote + " ".repeat(s.length - 2) + quote; + }); + }); + return code; +} + +function stripLiteral(code) { + try { + return stripLiteralAcorn(code); + } catch (e) { + return stripLiteralRegex(code); + } +} + +export { createIsLiteralPositionAcorn, stripLiteral, stripLiteralAcorn, stripLiteralRegex }; diff --git a/node_modules/strip-literal/package.json b/node_modules/strip-literal/package.json new file mode 100644 index 0000000..7ffde3f --- /dev/null +++ b/node_modules/strip-literal/package.json @@ -0,0 +1,62 @@ +{ + "name": "strip-literal", + "version": "1.0.0", + "packageManager": "pnpm@7.0.0", + "description": "Strip comments and string literals from JavaScript code", + "author": "Anthony Fu ", + "license": "MIT", + "funding": "https://github.com/sponsors/antfu", + "homepage": "https://github.com/antfu/strip-literal#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/antfu/strip-literal.git" + }, + "bugs": { + "url": "https://github.com/antfu/strip-literal/issues" + }, + "keywords": [], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.cjs", + "import": "./dist/index.mjs" + } + }, + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "build": "unbuild", + "dev": "unbuild --stub", + "lint": "eslint .", + "prepublishOnly": "nr build", + "release": "bumpp --commit --push --tag && npm publish", + "start": "esmo src/index.ts", + "test": "vitest", + "bench": "vitest bench", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "acorn": "^8.8.1" + }, + "devDependencies": { + "@antfu/eslint-config": "^0.30.1", + "@antfu/ni": "^0.18.5", + "@types/node": "^18.11.9", + "bumpp": "^8.2.1", + "eslint": "^8.27.0", + "esmo": "^0.16.3", + "pnpm": "^7.16.0", + "rimraf": "^3.0.2", + "three": "^0.146.0", + "typescript": "^4.8.4", + "unbuild": "^0.9.4", + "vite": "^3.2.3", + "vitest": "^0.25.2", + "vue": "^3.2.45" + } +} diff --git a/node_modules/supports-color/browser.js b/node_modules/supports-color/browser.js new file mode 100644 index 0000000..62afa3a --- /dev/null +++ b/node_modules/supports-color/browser.js @@ -0,0 +1,5 @@ +'use strict'; +module.exports = { + stdout: false, + stderr: false +}; diff --git a/node_modules/supports-color/index.js b/node_modules/supports-color/index.js new file mode 100644 index 0000000..6fada39 --- /dev/null +++ b/node_modules/supports-color/index.js @@ -0,0 +1,135 @@ +'use strict'; +const os = require('os'); +const tty = require('tty'); +const hasFlag = require('has-flag'); + +const {env} = process; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; +} + +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; diff --git a/node_modules/supports-color/license b/node_modules/supports-color/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/supports-color/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/supports-color/package.json b/node_modules/supports-color/package.json new file mode 100644 index 0000000..f7182ed --- /dev/null +++ b/node_modules/supports-color/package.json @@ -0,0 +1,53 @@ +{ + "name": "supports-color", + "version": "7.2.0", + "description": "Detect whether a terminal supports color", + "license": "MIT", + "repository": "chalk/supports-color", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "browser.js" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "dependencies": { + "has-flag": "^4.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "import-fresh": "^3.0.0", + "xo": "^0.24.0" + }, + "browser": "browser.js" +} diff --git a/node_modules/supports-color/readme.md b/node_modules/supports-color/readme.md new file mode 100644 index 0000000..3654228 --- /dev/null +++ b/node_modules/supports-color/readme.md @@ -0,0 +1,76 @@ +# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color) + +> Detect whether a terminal supports color + + +## Install + +``` +$ npm install supports-color +``` + + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- diff --git a/node_modules/supports-preserve-symlinks-flag/.eslintrc b/node_modules/supports-preserve-symlinks-flag/.eslintrc new file mode 100644 index 0000000..346ffec --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/.eslintrc @@ -0,0 +1,14 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "browser": true, + "node": true, + }, + + "rules": { + "id-length": "off", + }, +} diff --git a/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml b/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml new file mode 100644 index 0000000..e8d64f3 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/.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/supports-preserve-symlink-flag +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/supports-preserve-symlinks-flag/.nycrc b/node_modules/supports-preserve-symlinks-flag/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md b/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md new file mode 100644 index 0000000..61f607f --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md @@ -0,0 +1,22 @@ +# 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 - 2022-01-02 + +### Commits + +- Tests [`e2f59ad`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/e2f59ad74e2ae0f5f4899fcde6a6f693ab7cc074) +- Initial commit [`dc222aa`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/dc222aad3c0b940d8d3af1ca9937d108bd2dc4b9) +- [meta] do not publish workflow files [`5ef77f7`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/5ef77f7cb6946d16ee38672be9ec0f1bbdf63262) +- npm init [`992b068`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/992b068503a461f7e8676f40ca2aab255fd8d6ff) +- read me [`6c9afa9`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/6c9afa9fabc8eaf0814aaed6dd01e6df0931b76d) +- Initial implementation [`2f98925`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/2f9892546396d4ab0ad9f1ff83e76c3f01234ae8) +- [meta] add `auto-changelog` [`6c476ae`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/6c476ae1ed7ce68b0480344f090ac2844f35509d) +- [Dev Deps] add `eslint`, `@ljharb/eslint-config` [`d0fffc8`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/d0fffc886d25fba119355520750a909d64da0087) +- Only apps should have lockfiles [`ab318ed`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/ab318ed7ae62f6c2c0e80a50398d40912afd8f69) +- [meta] add `safe-publish-latest` [`2bb23b3`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/2bb23b3ebab02dc4135c4cdf0217db82835b9fca) +- [meta] add `sideEffects` flag [`600223b`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/600223ba24f30779f209d9097721eff35ed62741) diff --git a/node_modules/supports-preserve-symlinks-flag/LICENSE b/node_modules/supports-preserve-symlinks-flag/LICENSE new file mode 100644 index 0000000..2e7b9a3 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/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/supports-preserve-symlinks-flag/README.md b/node_modules/supports-preserve-symlinks-flag/README.md new file mode 100644 index 0000000..eb05b12 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/README.md @@ -0,0 +1,42 @@ +# node-supports-preserve-symlinks-flag [![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] + +Determine if the current node version supports the `--preserve-symlinks` flag. + +## Example + +```js +var supportsPreserveSymlinks = require('node-supports-preserve-symlinks-flag'); +var assert = require('assert'); + +assert.equal(supportsPreserveSymlinks, null); // in a browser +assert.equal(supportsPreserveSymlinks, false); // in node < v6.2 +assert.equal(supportsPreserveSymlinks, true); // in node v6.2+ +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/node-supports-preserve-symlinks-flag +[npm-version-svg]: https://versionbadg.es/inspect-js/node-supports-preserve-symlinks-flag.svg +[deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag.svg +[deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag +[dev-deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/node-supports-preserve-symlinks-flag.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/node-supports-preserve-symlinks-flag.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/node-supports-preserve-symlinks-flag.svg +[downloads-url]: https://npm-stat.com/charts.html?package=node-supports-preserve-symlinks-flag +[codecov-image]: https://codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/node-supports-preserve-symlinks-flag +[actions-url]: https://github.com/inspect-js/node-supports-preserve-symlinks-flag/actions diff --git a/node_modules/supports-preserve-symlinks-flag/browser.js b/node_modules/supports-preserve-symlinks-flag/browser.js new file mode 100644 index 0000000..087be1f --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/browser.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = null; diff --git a/node_modules/supports-preserve-symlinks-flag/index.js b/node_modules/supports-preserve-symlinks-flag/index.js new file mode 100644 index 0000000..86fd5d3 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/index.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = ( +// node 12+ + process.allowedNodeEnvironmentFlags && process.allowedNodeEnvironmentFlags.has('--preserve-symlinks') +) || ( +// node v6.2 - v11 + String(module.constructor._findPath).indexOf('preserveSymlinks') >= 0 // eslint-disable-line no-underscore-dangle +); diff --git a/node_modules/supports-preserve-symlinks-flag/package.json b/node_modules/supports-preserve-symlinks-flag/package.json new file mode 100644 index 0000000..56edadc --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/package.json @@ -0,0 +1,70 @@ +{ + "name": "supports-preserve-symlinks-flag", + "version": "1.0.0", + "description": "Determine if the current node version supports the `--preserve-symlinks` flag.", + "main": "./index.js", + "browser": "./browser.js", + "exports": { + ".": [ + { + "browser": "./browser.js", + "default": "./index.js" + }, + "./index.js" + ], + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "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/inspect-js/node-supports-preserve-symlinks-flag.git" + }, + "keywords": [ + "node", + "flag", + "symlink", + "symlinks", + "preserve-symlinks" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/node-supports-preserve-symlinks-flag/issues" + }, + "homepage": "https://github.com/inspect-js/node-supports-preserve-symlinks-flag#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.1.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "eslint": "^8.6.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "semver": "^6.3.0", + "tape": "^5.4.0" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/supports-preserve-symlinks-flag/test/index.js b/node_modules/supports-preserve-symlinks-flag/test/index.js new file mode 100644 index 0000000..9938d67 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/test/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); +var semver = require('semver'); + +var supportsPreserveSymlinks = require('../'); +var browser = require('../browser'); + +test('supportsPreserveSymlinks', function (t) { + t.equal(typeof supportsPreserveSymlinks, 'boolean', 'is a boolean'); + + t.equal(browser, null, 'browser file is `null`'); + t.equal( + supportsPreserveSymlinks, + null, + 'in a browser, is null', + { skip: typeof window === 'undefined' } + ); + + var expected = semver.satisfies(process.version, '>= 6.2'); + t.equal( + supportsPreserveSymlinks, + expected, + 'is true in node v6.2+, false otherwise (actual: ' + supportsPreserveSymlinks + ', expected ' + expected + ')', + { skip: typeof window !== 'undefined' } + ); + + t.end(); +}); diff --git a/node_modules/tinybench/LICENSE b/node_modules/tinybench/LICENSE new file mode 100644 index 0000000..64143b8 --- /dev/null +++ b/node_modules/tinybench/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Tinylibs + +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/tinybench/README.md b/node_modules/tinybench/README.md new file mode 100644 index 0000000..98d1c04 --- /dev/null +++ b/node_modules/tinybench/README.md @@ -0,0 +1,332 @@ +# tinybench + +Benchmark your code easily with Tinybench, a simple, tiny and light-weight `7KB` (`2KB` minified and gzipped) +benchmarking library! +You can run your benchmarks in multiple JavaScript runtimes, Tinybench is +completely based on the Web APIs with proper timing using `process.hrtime` or +`performance.now`. + +- Accurate and precise timing based on the environment +- `Event` and `EventTarget` compatible events +- Statistically analyzed values +- Calculated Percentiles +- Fully detailed results +- No dependencies + +_In case you need more tiny libraries like tinypool or tinyspy, please consider submitting an [RFC](https://github.com/tinylibs/rfcs)_ + +## Installing + +```bash +$ npm install -D tinybench +``` + +## Usage + +You can start benchmarking by instantiating the `Bench` class and adding +benchmark tasks to it. + +```ts +import { Bench } from 'tinybench'; + +const bench = new Bench({ time: 100 }); + +bench + .add('switch 1', () => { + let a = 1; + let b = 2; + const c = a; + a = b; + b = c; + }) + .add('switch 2', () => { + let a = 1; + let b = 10; + a = b + a; + b = a - b; + a = b - a; + }); + +await bench.run(); + +console.table(bench.tasks.map(({ name, result }) => ({ "Task Name": name, "Average Time (ps)": result?.mean! * 1000, "Variance (ps)": result?.variance! * 1000 }))); + +// Output: +// ┌─────────┬────────────┬────────────────────┬────────────────────┐ +// │ (index) │ Task Name │ Average Time (ps) │ Variance (ps) │ +// ├─────────┼────────────┼────────────────────┼────────────────────┤ +// │ 0 │ 'switch 1' │ 1.8458325710527104 │ 1.2113875253341617 │ +// │ 1 │ 'switch 2' │ 1.8746935152109603 │ 1.2254725890767446 │ +// └─────────┴────────────┴────────────────────┴────────────────────┘ +``` + +The `add` method accepts a task name and a task function, so it can benchmark +it! This method returns a reference to the Bench instance, so it's possible to +use it to create an another task for that instance. + +Note that the task name should always be unique in an instance, because Tinybench stores the tasks based +on their names in a `Map`. + +Also note that `tinybench` does not log any result by default. You can extract the relevant stats +from `bench.tasks` or any other API after running the benchmark, and process them however you want. + +## Docs + +### `Bench` + +The Benchmark instance for keeping track of the benchmark tasks and controlling +them. + +Options: + +```ts +export type Options = { + /** + * time needed for running a benchmark task (milliseconds) @default 500 + */ + time?: number; + + /** + * number of times that a task should run if even the time option is finished @default 10 + */ + iterations?: number; + + /** + * function to get the current timestamp in milliseconds + */ + now?: () => number; + + /** + * An AbortSignal for aborting the benchmark + */ + signal?: AbortSignal; + + /** + * warmup time (milliseconds) @default 100ms + */ + warmupTime?: number; + + /** + * warmup iterations @default 5 + */ + warmupIterations?: number; + + /** + * setup function to run before each benchmark task (cycle) + */ + setup?: Hook; + + /** + * teardown function to run after each benchmark task (cycle) + */ + teardown?: Hook; +}; + +export type Hook = (task: Task, mode: "warmup" | "run") => void | Promise; +``` + +- `async run()`: run the added tasks that were registered using the `add` method +- `async warmup()`: warm up the benchmark tasks +- `reset()`: reset each task and remove its result +- `add(name: string, fn: Fn)`: add a benchmark task to the task map +- - `Fn`: `() => any | Promise` +- `remove(name: string)`: remove a benchmark task from the task map +- `get results(): (TaskResult | undefined)[]`: (getter) tasks results as an array +- `get tasks(): Task[]`: (getter) tasks as an array +- `getTask(name: string): Task | undefined`: get a task based on the name + +### `Task` + +A class that represents each benchmark task in Tinybench. It keeps track of the +results, name, Bench instance, the task function and the number of times the task +function has been executed. + +- `constructor(bench: Bench, name: string, fn: Fn)` +- `bench: Bench` +- `name: string`: task name +- `fn: Fn`: the task function +- `runs: number`: the number of times the task function has been executed +- `result?: TaskResult`: the result object +- `async run()`: run the current task and write the results in `Task.result` object +- `async warmup()`: warm up the current task +- `setResult(result: Partial)`: change the result object values +- `reset()`: reset the task to make the `Task.runs` a zero-value and remove the `Task.result` object + +## `TaskResult` + +the benchmark task result object. + +```ts +export type TaskResult = { + + /* + * the last error that was thrown while running the task + */ + error?: unknown; + + /** + * The amount of time in milliseconds to run the benchmark task (cycle). + */ + totalTime: number; + + /** + * the minimum value in the samples + */ + min: number; + /** + * the maximum value in the samples + */ + max: number; + + /** + * the number of operations per second + */ + hz: number; + + /** + * how long each operation takes (ms) + */ + period: number; + + /** + * task samples of each task iteration time (ms) + */ + samples: number[]; + + /** + * samples mean/average (estimate of the population mean) + */ + mean: number; + + /** + * samples variance (estimate of the population variance) + */ + variance: number; + + /** + * samples standard deviation (estimate of the population standard deviation) + */ + sd: number; + + /** + * standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean) + */ + sem: number; + + /** + * degrees of freedom + */ + df: number; + + /** + * critical value of the samples + */ + critical: number; + + /** + * margin of error + */ + moe: number; + + /** + * relative margin of error + */ + rme: number; + + /** + * p75 percentile + */ + p75: number; + + /** + * p99 percentile + */ + p99: number; + + /** + * p995 percentile + */ + p995: number; + + /** + * p999 percentile + */ + p999: number; +}; +``` + +### `Events` + +Both the `Task` and `Bench` objects extend the `EventTarget` object, so you can attach listeners to different types of events +in each class instance using the universal `addEventListener` and +`removeEventListener`. + +```ts +/** + * Bench events + */ +export type BenchEvents = + | "abort" // when a signal aborts + | "complete" // when running a benchmark finishes + | "error" // when the benchmark task throws + | "reset" // when the reset function gets called + | "start" // when running the benchmarks gets started + | "warmup" // when the benchmarks start getting warmed up (before start) + | "cycle" // when running each benchmark task gets done (cycle) + | "add" // when a Task gets added to the Bench + | "remove"; // when a Task gets removed of the Bench + +/** + * task events + */ +export type TaskEvents = + | "abort" + | "complete" + | "error" + | "reset" + | "start" + | "warmup" + | "cycle"; +``` + +For instance: + +```ts +// runs on each benchmark task's cycle +bench.addEventListener("cycle", (e: BenchEvent) => { + const task = e.task!; +}); + +// runs only on this benchmark task's cycle +task.addEventListener("cycle", (e: BenchEvent) => { + const task = e.task!; +}); +``` + +### `BenchEvent` + +```ts +export type BenchEvent = Event & { + task: Task | null; +}; +``` + +## Prior art + +- [Benchmark.js](https://github.com/bestiejs/benchmark.js) +- [Mitata](https://github.com/evanwashere/mitata/) +- [Bema](https://github.com/prisma-labs/bema) + +## Authors + +|
Mohammad Bagher
| +| ------------------------------------------------------------------------------------------------------------------------------------------------ | + +## Credits + +|
Uzlopak
|
poyoho
| +| ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | + +## Contributing + +Feel free to create issues/discussions and then PRs for the project! diff --git a/node_modules/tinybench/dist/index.cjs b/node_modules/tinybench/dist/index.cjs new file mode 100644 index 0000000..af8d891 --- /dev/null +++ b/node_modules/tinybench/dist/index.cjs @@ -0,0 +1,322 @@ +"use strict"; +var f = Object.defineProperty; +var H = Object.getOwnPropertyDescriptor; +var P = Object.getOwnPropertyNames; +var S = Object.prototype.hasOwnProperty; +var j = (n, r, t) => r in n ? f(n, r, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[r] = t; +var q = (n, r) => { + for (var t in r) + f(n, t, { get: r[t], enumerable: !0 }); +}, z = (n, r, t, e) => { + if (r && typeof r == "object" || typeof r == "function") + for (let s of P(r)) + !S.call(n, s) && s !== t && f(n, s, { get: () => r[s], enumerable: !(e = H(r, s)) || e.enumerable }); + return n; +}; +var V = (n) => z(f({}, "__esModule", { value: !0 }), n); +var a = (n, r, t) => (j(n, typeof r != "symbol" ? r + "" : r, t), t); + +// src/index.ts +var J = {}; +q(J, { + Bench: () => p, + Task: () => c, + default: () => G, + now: () => E +}); +module.exports = V(J); + +// src/event.ts +function i(n, r = null) { + let t = new Event(n); + return Object.defineProperty(t, "task", { + value: r, + enumerable: !0, + writable: !1, + configurable: !1 + }), t; +} + +// src/constants.ts +var C = { + 1: 12.71, + 2: 4.303, + 3: 3.182, + 4: 2.776, + 5: 2.571, + 6: 2.447, + 7: 2.365, + 8: 2.306, + 9: 2.262, + 10: 2.228, + 11: 2.201, + 12: 2.179, + 13: 2.16, + 14: 2.145, + 15: 2.131, + 16: 2.12, + 17: 2.11, + 18: 2.101, + 19: 2.093, + 20: 2.086, + 21: 2.08, + 22: 2.074, + 23: 2.069, + 24: 2.064, + 25: 2.06, + 26: 2.056, + 27: 2.052, + 28: 2.048, + 29: 2.045, + 30: 2.042, + 31: 2.0399, + 32: 2.0378, + 33: 2.0357, + 34: 2.0336, + 35: 2.0315, + 36: 2.0294, + 37: 2.0273, + 38: 2.0252, + 39: 2.0231, + 40: 2.021, + 41: 2.0198, + 42: 2.0186, + 43: 2.0174, + 44: 2.0162, + 45: 2.015, + 46: 2.0138, + 47: 2.0126, + 48: 2.0114, + 49: 2.0102, + 50: 2.009, + 51: 2.0081, + 52: 2.0072, + 53: 2.0063, + 54: 2.0054, + 55: 2.0045, + 56: 2.0036, + 57: 2.0027, + 58: 2.0018, + 59: 2.0009, + 60: 2, + 61: 1.9995, + 62: 1.999, + 63: 1.9985, + 64: 1.998, + 65: 1.9975, + 66: 1.997, + 67: 1.9965, + 68: 1.996, + 69: 1.9955, + 70: 1.995, + 71: 1.9945, + 72: 1.994, + 73: 1.9935, + 74: 1.993, + 75: 1.9925, + 76: 1.992, + 77: 1.9915, + 78: 1.991, + 79: 1.9905, + 80: 1.99, + 81: 1.9897, + 82: 1.9894, + 83: 1.9891, + 84: 1.9888, + 85: 1.9885, + 86: 1.9882, + 87: 1.9879, + 88: 1.9876, + 89: 1.9873, + 90: 1.987, + 91: 1.9867, + 92: 1.9864, + 93: 1.9861, + 94: 1.9858, + 95: 1.9855, + 96: 1.9852, + 97: 1.9849, + 98: 1.9846, + 99: 1.9843, + 100: 1.984, + 101: 1.9838, + 102: 1.9836, + 103: 1.9834, + 104: 1.9832, + 105: 1.983, + 106: 1.9828, + 107: 1.9826, + 108: 1.9824, + 109: 1.9822, + 110: 1.982, + 111: 1.9818, + 112: 1.9816, + 113: 1.9814, + 114: 1.9812, + 115: 1.9819, + 116: 1.9808, + 117: 1.9806, + 118: 1.9804, + 119: 1.9802, + 120: 1.98, + infinity: 1.96 +}, w = C; + +// src/utils.ts +var N = (n) => n / 1e6, E = () => { + var n; + return typeof ((n = globalThis.process) == null ? void 0 : n.hrtime) == "function" ? N(Number(process.hrtime.bigint())) : performance.now(); +}, B = (n) => n.reduce((r, t) => r + t, 0) / n.length || 0, L = (n, r) => n.reduce((e, s) => e + (s - r) ** 2) / (n.length - 1) || 0, D = (async () => { +}).constructor, K = (n) => n.constructor === D; + +// src/task.ts +var c = class extends EventTarget { + constructor(t, e, s) { + super(); + a(this, "bench"); + a(this, "name"); + a(this, "fn"); + a(this, "runs", 0); + a(this, "result"); + this.bench = t, this.name = e, this.fn = s; + } + async run() { + var u, l, m; + this.dispatchEvent(i("start", this)); + let t = 0, e = [], s = K(this.fn); + for (await this.bench.setup(this, "run"); (t < this.bench.time || this.runs < this.bench.iterations) && !((u = this.bench.signal) != null && u.aborted); ) { + let o = 0; + try { + o = this.bench.now(), s ? await this.fn() : this.fn(); + } catch (v) { + this.setResult({ error: v }); + } + let h = this.bench.now() - o; + this.runs += 1, e.push(h), t += h; + } + await this.bench.teardown(this, "run"), e.sort((o, h) => o - h); + { + let o = e[0], h = e[e.length - 1], v = t / this.runs, F = 1e3 / v, b = B(e), T = L(e, b), k = Math.sqrt(T), g = k / Math.sqrt(e.length), y = e.length - 1, x = w[String(Math.round(y) || 1)] || w.infinity, M = g * x, R = M / b * 100 || 0, O = e[Math.ceil(e.length * (75 / 100)) - 1], _ = e[Math.ceil(e.length * (99 / 100)) - 1], A = e[Math.ceil(e.length * (99.5 / 100)) - 1], I = e[Math.ceil(e.length * (99.9 / 100)) - 1]; + if ((l = this.bench.signal) != null && l.aborted) + return this; + this.setResult({ + totalTime: t, + min: o, + max: h, + hz: F, + period: v, + samples: e, + mean: b, + variance: T, + sd: k, + sem: g, + df: y, + critical: x, + moe: M, + rme: R, + p75: O, + p99: _, + p995: A, + p999: I + }); + } + return (m = this.result) != null && m.error && (this.dispatchEvent(i("error", this)), this.bench.dispatchEvent(i("error", this))), this.dispatchEvent(i("cycle", this)), this.bench.dispatchEvent(i("cycle", this)), this.dispatchEvent(i("complete", this)), this; + } + async warmup() { + var s; + this.dispatchEvent(i("warmup", this)); + let t = this.bench.now(), e = 0; + for (this.bench.setup(this, "warmup"); (e < this.bench.warmupTime || this.runs < this.bench.warmupIterations) && !((s = this.bench.signal) != null && s.aborted); ) { + try { + await Promise.resolve().then(this.fn); + } catch (u) { + } + this.runs += 1, e = this.bench.now() - t; + } + this.bench.teardown(this, "warmup"), this.runs = 0; + } + addEventListener(t, e, s) { + super.addEventListener(t, e, s); + } + removeEventListener(t, e, s) { + super.removeEventListener(t, e, s); + } + setResult(t) { + this.result = { ...this.result, ...t }, Object.freeze(this.reset); + } + reset() { + this.dispatchEvent(i("reset", this)), this.runs = 0, this.result = void 0; + } +}; + +// src/bench.ts +var p = class extends EventTarget { + constructor(t = {}) { + var e, s, u, l, m, o, h; + super(); + a(this, "_tasks", /* @__PURE__ */ new Map()); + a(this, "signal"); + a(this, "warmupTime", 100); + a(this, "warmupIterations", 5); + a(this, "time", 500); + a(this, "iterations", 10); + a(this, "now", E); + a(this, "setup"); + a(this, "teardown"); + this.now = (e = t.now) != null ? e : this.now, this.warmupTime = (s = t.warmupTime) != null ? s : this.warmupTime, this.warmupIterations = (u = t.warmupIterations) != null ? u : this.warmupIterations, this.time = (l = t.time) != null ? l : this.time, this.iterations = (m = t.iterations) != null ? m : this.iterations, this.signal = t.signal, this.setup = (o = t.setup) != null ? o : () => { + }, this.teardown = (h = t.teardown) != null ? h : () => { + }, this.signal && this.signal.addEventListener("abort", () => { + this.dispatchEvent(i("abort")); + }, { once: !0 }); + } + async run() { + var e; + this.dispatchEvent(i("start")); + let t = []; + for (let s of [...this._tasks.values()]) + (e = this.signal) != null && e.aborted ? t.push(s) : t.push(await s.run()); + return this.dispatchEvent(i("complete")), t; + } + async warmup() { + this.dispatchEvent(i("warmup")); + for (let [, t] of this._tasks) + await t.warmup(); + } + reset() { + this.dispatchEvent(i("reset")), this._tasks.forEach((t) => { + t.reset(); + }); + } + add(t, e) { + let s = new c(this, t, e); + return this._tasks.set(t, s), this.dispatchEvent(i("add", s)), this; + } + remove(t) { + let e = this.getTask(t); + return this.dispatchEvent(i("remove", e)), this._tasks.delete(t), this; + } + addEventListener(t, e, s) { + super.addEventListener(t, e, s); + } + removeEventListener(t, e, s) { + super.removeEventListener(t, e, s); + } + get results() { + return [...this._tasks.values()].map((t) => t.result); + } + get tasks() { + return [...this._tasks.values()]; + } + getTask(t) { + return this._tasks.get(t); + } +}; + +// src/index.ts +var G = p; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Bench, + Task, + now +}); diff --git a/node_modules/tinybench/dist/index.d.ts b/node_modules/tinybench/dist/index.d.ts new file mode 100644 index 0000000..e17845f --- /dev/null +++ b/node_modules/tinybench/dist/index.d.ts @@ -0,0 +1,305 @@ +/** + * A class that represents each benchmark task in Tinybench. It keeps track of the + * results, name, Bench instance, the task function and the number times the task + * function has been executed. + */ +declare class Task extends EventTarget { + bench: Bench; + /** + * task name + */ + name: string; + fn: Fn; + runs: number; + /** + * the result object + */ + result?: TaskResult; + constructor(bench: Bench, name: string, fn: Fn); + /** + * run the current task and write the results in `Task.result` object + */ + run(): Promise; + /** + * warmup the current task + */ + warmup(): Promise; + addEventListener(type: K, listener: T, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: T, options?: boolean | EventListenerOptions): void; + /** + * change the result object values + */ + setResult(result: Partial): void; + /** + * reset the task to make the `Task.runs` a zero-value and remove the `Task.result` + * object + */ + reset(): void; +} + +/** + * the task function + */ +type Fn = () => any | Promise; + +/** + * the benchmark task result object + */ +type TaskResult = { + /* + * the last error that was thrown while running the task + */ + error?: unknown; + + /** + * The amount of time in milliseconds to run the benchmark task (cycle). + */ + totalTime: number; + + /** + * the minimum value in the samples + */ + min: number; + /** + * the maximum value in the samples + */ + max: number; + + /** + * the number of operations per second + */ + hz: number; + + /** + * how long each operation takes (ms) + */ + period: number; + + /** + * task samples of each task iteration time (ms) + */ + samples: number[]; + + /** + * samples mean/average (estimate of the population mean) + */ + mean: number; + + /** + * samples variance (estimate of the population variance) + */ + variance: number; + + /** + * samples standard deviation (estimate of the population standard deviation) + */ + sd: number; + + /** + * standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean) + */ + sem: number; + + /** + * degrees of freedom + */ + df: number; + + /** + * critical value of the samples + */ + critical: number; + + /** + * margin of error + */ + moe: number; + + /** + * relative margin of error + */ + rme: number; + + /** + * p75 percentile + */ + p75: number; + + /** + * p99 percentile + */ + p99: number; + + /** + * p995 percentile + */ + p995: number; + + /** + * p999 percentile + */ + p999: number; +}; + +/** + * Both the `Task` and `Bench` objects extend the `EventTarget` object, + * so you can attach a listeners to different types of events + * to each class instance using the universal `addEventListener` and + * `removeEventListener` + */ + +/** + * Bench events + */ +type BenchEvents = + | 'abort' // when a signal aborts + | 'complete' // when running a benchmark finishes + | 'error' // when the benchmark task throws + | 'reset' // when the reset function gets called + | 'start' // when running the benchmarks gets started + | 'warmup' // when the benchmarks start getting warmed up (before start) + | 'cycle' // when running each benchmark task gets done (cycle) + | 'add' // when a Task gets added to the Bench + | 'remove'; // when a Task gets removed of the Bench + +type Hook = (task: Task, mode: 'warmup' | 'run') => void | Promise; + +type NoopEventListener = () => any | Promise +type TaskEventListener = (e: Event & { task: Task }) => any | Promise + +interface BenchEventsMap{ + abort: NoopEventListener + start: NoopEventListener + complete: NoopEventListener + warmup: NoopEventListener + reset: NoopEventListener + add: TaskEventListener + remove: TaskEventListener + cycle: TaskEventListener + error: TaskEventListener +} + +/** + * task events + */ +type TaskEvents = + | 'abort' + | 'complete' + | 'error' + | 'reset' + | 'start' + | 'warmup' + | 'cycle'; + +type TaskEventsMap = { + abort: NoopEventListener + start: TaskEventListener + error: TaskEventListener + cycle: TaskEventListener + complete: TaskEventListener + warmup: TaskEventListener + reset: TaskEventListener +} +type Options = { + /** + * time needed for running a benchmark task (milliseconds) @default 500 + */ + time?: number; + + /** + * number of times that a task should run if even the time option is finished @default 10 + */ + iterations?: number; + + /** + * function to get the current timestamp in milliseconds + */ + now?: () => number; + + /** + * An AbortSignal for aborting the benchmark + */ + signal?: AbortSignal; + + /** + * warmup time (milliseconds) @default 100ms + */ + warmupTime?: number; + + /** + * warmup iterations @default 5 + */ + warmupIterations?: number; + + /** + * setup function to run before each benchmark task (cycle) + */ + setup?: Hook; + + /** + * teardown function to run after each benchmark task (cycle) + */ + teardown?: Hook; +}; + +type BenchEvent = Event & { + task: Task | null; +}; + +/** + * The Benchmark instance for keeping track of the benchmark tasks and controlling + * them. + */ +declare class Bench extends EventTarget { + _tasks: Map; + signal?: AbortSignal; + warmupTime: number; + warmupIterations: number; + time: number; + iterations: number; + now: () => number; + setup: Hook; + teardown: Hook; + constructor(options?: Options); + /** + * run the added tasks that were registered using the + * {@link add} method. + * Note: This method does not do any warmup. Call {@link warmup} for that. + */ + run(): Promise; + /** + * warmup the benchmark tasks. + * This is not run by default by the {@link run} method. + */ + warmup(): Promise; + /** + * reset each task and remove its result + */ + reset(): void; + /** + * add a benchmark task to the task map + */ + add(name: string, fn: Fn): this; + /** + * remove a benchmark task from the task map + */ + remove(name: string): this; + addEventListener(type: K, listener: T, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: T, options?: boolean | EventListenerOptions): void; + /** + * (getter) tasks results as an array + */ + get results(): (TaskResult | undefined)[]; + /** + * (getter) tasks as an array + */ + get tasks(): Task[]; + /** + * get a task based on the task name + */ + getTask(name: string): Task | undefined; +} + +declare const now: () => number; + +export { Bench, BenchEvent, BenchEvents, Fn, Hook, Options, Task, TaskEvents, TaskResult, Bench as default, now }; diff --git a/node_modules/tinybench/dist/index.js b/node_modules/tinybench/dist/index.js new file mode 100644 index 0000000..5e0c6d2 --- /dev/null +++ b/node_modules/tinybench/dist/index.js @@ -0,0 +1,298 @@ +var H = Object.defineProperty; +var P = (n, a, t) => a in n ? H(n, a, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[a] = t; +var i = (n, a, t) => (P(n, typeof a != "symbol" ? a + "" : a, t), t); + +// src/event.ts +function r(n, a = null) { + let t = new Event(n); + return Object.defineProperty(t, "task", { + value: a, + enumerable: !0, + writable: !1, + configurable: !1 + }), t; +} + +// src/constants.ts +var S = { + 1: 12.71, + 2: 4.303, + 3: 3.182, + 4: 2.776, + 5: 2.571, + 6: 2.447, + 7: 2.365, + 8: 2.306, + 9: 2.262, + 10: 2.228, + 11: 2.201, + 12: 2.179, + 13: 2.16, + 14: 2.145, + 15: 2.131, + 16: 2.12, + 17: 2.11, + 18: 2.101, + 19: 2.093, + 20: 2.086, + 21: 2.08, + 22: 2.074, + 23: 2.069, + 24: 2.064, + 25: 2.06, + 26: 2.056, + 27: 2.052, + 28: 2.048, + 29: 2.045, + 30: 2.042, + 31: 2.0399, + 32: 2.0378, + 33: 2.0357, + 34: 2.0336, + 35: 2.0315, + 36: 2.0294, + 37: 2.0273, + 38: 2.0252, + 39: 2.0231, + 40: 2.021, + 41: 2.0198, + 42: 2.0186, + 43: 2.0174, + 44: 2.0162, + 45: 2.015, + 46: 2.0138, + 47: 2.0126, + 48: 2.0114, + 49: 2.0102, + 50: 2.009, + 51: 2.0081, + 52: 2.0072, + 53: 2.0063, + 54: 2.0054, + 55: 2.0045, + 56: 2.0036, + 57: 2.0027, + 58: 2.0018, + 59: 2.0009, + 60: 2, + 61: 1.9995, + 62: 1.999, + 63: 1.9985, + 64: 1.998, + 65: 1.9975, + 66: 1.997, + 67: 1.9965, + 68: 1.996, + 69: 1.9955, + 70: 1.995, + 71: 1.9945, + 72: 1.994, + 73: 1.9935, + 74: 1.993, + 75: 1.9925, + 76: 1.992, + 77: 1.9915, + 78: 1.991, + 79: 1.9905, + 80: 1.99, + 81: 1.9897, + 82: 1.9894, + 83: 1.9891, + 84: 1.9888, + 85: 1.9885, + 86: 1.9882, + 87: 1.9879, + 88: 1.9876, + 89: 1.9873, + 90: 1.987, + 91: 1.9867, + 92: 1.9864, + 93: 1.9861, + 94: 1.9858, + 95: 1.9855, + 96: 1.9852, + 97: 1.9849, + 98: 1.9846, + 99: 1.9843, + 100: 1.984, + 101: 1.9838, + 102: 1.9836, + 103: 1.9834, + 104: 1.9832, + 105: 1.983, + 106: 1.9828, + 107: 1.9826, + 108: 1.9824, + 109: 1.9822, + 110: 1.982, + 111: 1.9818, + 112: 1.9816, + 113: 1.9814, + 114: 1.9812, + 115: 1.9819, + 116: 1.9808, + 117: 1.9806, + 118: 1.9804, + 119: 1.9802, + 120: 1.98, + infinity: 1.96 +}, b = S; + +// src/utils.ts +var j = (n) => n / 1e6, w = () => { + var n; + return typeof ((n = globalThis.process) == null ? void 0 : n.hrtime) == "function" ? j(Number(process.hrtime.bigint())) : performance.now(); +}, B = (n) => n.reduce((a, t) => a + t, 0) / n.length || 0, L = (n, a) => n.reduce((e, s) => e + (s - a) ** 2) / (n.length - 1) || 0, q = (async () => { +}).constructor, K = (n) => n.constructor === q; + +// src/task.ts +var u = class extends EventTarget { + constructor(t, e, s) { + super(); + i(this, "bench"); + i(this, "name"); + i(this, "fn"); + i(this, "runs", 0); + i(this, "result"); + this.bench = t, this.name = e, this.fn = s; + } + async run() { + var c, p, l; + this.dispatchEvent(r("start", this)); + let t = 0, e = [], s = K(this.fn); + for (await this.bench.setup(this, "run"); (t < this.bench.time || this.runs < this.bench.iterations) && !((c = this.bench.signal) != null && c.aborted); ) { + let o = 0; + try { + o = this.bench.now(), s ? await this.fn() : this.fn(); + } catch (f) { + this.setResult({ error: f }); + } + let h = this.bench.now() - o; + this.runs += 1, e.push(h), t += h; + } + await this.bench.teardown(this, "run"), e.sort((o, h) => o - h); + { + let o = e[0], h = e[e.length - 1], f = t / this.runs, F = 1e3 / f, E = B(e), T = L(e, E), k = Math.sqrt(T), g = k / Math.sqrt(e.length), y = e.length - 1, x = b[String(Math.round(y) || 1)] || b.infinity, M = g * x, R = M / E * 100 || 0, O = e[Math.ceil(e.length * (75 / 100)) - 1], _ = e[Math.ceil(e.length * (99 / 100)) - 1], A = e[Math.ceil(e.length * (99.5 / 100)) - 1], I = e[Math.ceil(e.length * (99.9 / 100)) - 1]; + if ((p = this.bench.signal) != null && p.aborted) + return this; + this.setResult({ + totalTime: t, + min: o, + max: h, + hz: F, + period: f, + samples: e, + mean: E, + variance: T, + sd: k, + sem: g, + df: y, + critical: x, + moe: M, + rme: R, + p75: O, + p99: _, + p995: A, + p999: I + }); + } + return (l = this.result) != null && l.error && (this.dispatchEvent(r("error", this)), this.bench.dispatchEvent(r("error", this))), this.dispatchEvent(r("cycle", this)), this.bench.dispatchEvent(r("cycle", this)), this.dispatchEvent(r("complete", this)), this; + } + async warmup() { + var s; + this.dispatchEvent(r("warmup", this)); + let t = this.bench.now(), e = 0; + for (this.bench.setup(this, "warmup"); (e < this.bench.warmupTime || this.runs < this.bench.warmupIterations) && !((s = this.bench.signal) != null && s.aborted); ) { + try { + await Promise.resolve().then(this.fn); + } catch (c) { + } + this.runs += 1, e = this.bench.now() - t; + } + this.bench.teardown(this, "warmup"), this.runs = 0; + } + addEventListener(t, e, s) { + super.addEventListener(t, e, s); + } + removeEventListener(t, e, s) { + super.removeEventListener(t, e, s); + } + setResult(t) { + this.result = { ...this.result, ...t }, Object.freeze(this.reset); + } + reset() { + this.dispatchEvent(r("reset", this)), this.runs = 0, this.result = void 0; + } +}; + +// src/bench.ts +var v = class extends EventTarget { + constructor(t = {}) { + var e, s, c, p, l, o, h; + super(); + i(this, "_tasks", /* @__PURE__ */ new Map()); + i(this, "signal"); + i(this, "warmupTime", 100); + i(this, "warmupIterations", 5); + i(this, "time", 500); + i(this, "iterations", 10); + i(this, "now", w); + i(this, "setup"); + i(this, "teardown"); + this.now = (e = t.now) != null ? e : this.now, this.warmupTime = (s = t.warmupTime) != null ? s : this.warmupTime, this.warmupIterations = (c = t.warmupIterations) != null ? c : this.warmupIterations, this.time = (p = t.time) != null ? p : this.time, this.iterations = (l = t.iterations) != null ? l : this.iterations, this.signal = t.signal, this.setup = (o = t.setup) != null ? o : () => { + }, this.teardown = (h = t.teardown) != null ? h : () => { + }, this.signal && this.signal.addEventListener("abort", () => { + this.dispatchEvent(r("abort")); + }, { once: !0 }); + } + async run() { + var e; + this.dispatchEvent(r("start")); + let t = []; + for (let s of [...this._tasks.values()]) + (e = this.signal) != null && e.aborted ? t.push(s) : t.push(await s.run()); + return this.dispatchEvent(r("complete")), t; + } + async warmup() { + this.dispatchEvent(r("warmup")); + for (let [, t] of this._tasks) + await t.warmup(); + } + reset() { + this.dispatchEvent(r("reset")), this._tasks.forEach((t) => { + t.reset(); + }); + } + add(t, e) { + let s = new u(this, t, e); + return this._tasks.set(t, s), this.dispatchEvent(r("add", s)), this; + } + remove(t) { + let e = this.getTask(t); + return this.dispatchEvent(r("remove", e)), this._tasks.delete(t), this; + } + addEventListener(t, e, s) { + super.addEventListener(t, e, s); + } + removeEventListener(t, e, s) { + super.removeEventListener(t, e, s); + } + get results() { + return [...this._tasks.values()].map((t) => t.result); + } + get tasks() { + return [...this._tasks.values()]; + } + getTask(t) { + return this._tasks.get(t); + } +}; + +// src/index.ts +var tt = v; +export { + v as Bench, + u as Task, + tt as default, + w as now +}; diff --git a/node_modules/tinybench/package.json b/node_modules/tinybench/package.json new file mode 100644 index 0000000..ab61757 --- /dev/null +++ b/node_modules/tinybench/package.json @@ -0,0 +1,28 @@ +{ + "name": "tinybench", + "version": "2.3.1", + "type": "module", + "packageManager": "pnpm@7.5.1", + "main": "./dist/index.cjs", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js", + "require": "./dist/index.cjs", + "default": "./dist/index.cjs" + }, + "files": [ + "dist/**" + ], + "repository": "tinylibs/tinybench", + "license": "MIT", + "keywords": [ + "benchmark", + "tinylibs", + "tiny" + ], + "scripts": { + "publish": "npm run build && clean-publish" + } +} diff --git a/node_modules/tinypool/LICENSE b/node_modules/tinypool/LICENSE new file mode 100644 index 0000000..9026cdf --- /dev/null +++ b/node_modules/tinypool/LICENSE @@ -0,0 +1,24 @@ +The MIT License (MIT) + +Copyright (c) 2020 James M Snell and the Piscina contributors + +Piscina contributors listed at https://github.com/jasnell/piscina#the-team and +in the README file. + +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/tinypool/README.md b/node_modules/tinypool/README.md new file mode 100644 index 0000000..da2e8dc --- /dev/null +++ b/node_modules/tinypool/README.md @@ -0,0 +1,19 @@ +# Tinypool - the node.js worker pool 🧵 + +> Piscina: A fast, efficient Node.js Worker Thread Pool implementation + +Tinypool is a fork of piscina. What we try to achieve in this library, is to eliminate some dependencies and features that our target users don't need (currently, our main user will be Vitest). Tinypool's install size (38KB) can then be smaller than Piscina's install size (6MB). If you need features like [utilization](https://github.com/piscinajs/piscina#property-utilization-readonly) or [NAPI](https://github.com/piscinajs/piscina#thread-priority-on-linux-systems), [Piscina](https://github.com/piscinajs/piscina) is a better choice for you. We think that Piscina is an amazing library, and we may try to upstream some of the dependencies optimization in this fork. + +- ✅ Smaller install size, 38KB +- ✅ Minimal +- ✅ No dependencies +- ✅ Physical cores instead of Logical cores with [physical-cpu-count](https://www.npmjs.com/package/physical-cpu-count) +- ❌ No utilization +- ❌ No NAPI + +- Written in TypeScript, and ESM support only. For Node.js 14.x and higher. + +_In case you need more tiny libraries like tinypool or tinyspy, please consider submitting an [RFC](https://github.com/tinylibs/rfcs)_ + +## Docs +Read **[full docs](https://github.com/aslemammad/tinypool#readme)** on GitHub. diff --git a/node_modules/tinypool/dist/esm/chunk-QYFJIXNO.js b/node_modules/tinypool/dist/esm/chunk-QYFJIXNO.js new file mode 100644 index 0000000..46dd0a0 --- /dev/null +++ b/node_modules/tinypool/dist/esm/chunk-QYFJIXNO.js @@ -0,0 +1,75 @@ +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; + +// node_modules/.pnpm/tsup@5.12.9_w42fuc5ytk33cxmvw2eywssbqm/node_modules/tsup/assets/esm_shims.js +import { fileURLToPath } from "url"; +import path from "path"; +var getFilename = () => fileURLToPath(import.meta.url); +var getDirname = () => path.dirname(getFilename()); +var __dirname = /* @__PURE__ */ getDirname(); + +// src/common.ts +var kMovable = Symbol("Tinypool.kMovable"); +var kTransferable = Symbol.for("Tinypool.transferable"); +var kValue = Symbol.for("Tinypool.valueOf"); +var kQueueOptions = Symbol.for("Tinypool.queueOptions"); +function isTransferable(value) { + return value != null && typeof value === "object" && kTransferable in value && kValue in value; +} +function isMovable(value) { + return isTransferable(value) && value[kMovable] === true; +} +function markMovable(value) { + Object.defineProperty(value, kMovable, { + enumerable: false, + configurable: true, + writable: true, + value: true + }); +} +function isTaskQueue(value) { + return typeof value === "object" && value !== null && "size" in value && typeof value.shift === "function" && typeof value.remove === "function" && typeof value.push === "function"; +} +var kRequestCountField = 0; +var kResponseCountField = 1; +var kFieldCount = 2; + +export { + __publicField, + __privateGet, + __privateAdd, + __privateSet, + __dirname, + kTransferable, + kValue, + kQueueOptions, + isTransferable, + isMovable, + markMovable, + isTaskQueue, + kRequestCountField, + kResponseCountField, + kFieldCount +}; diff --git a/node_modules/tinypool/dist/esm/index.js b/node_modules/tinypool/dist/esm/index.js new file mode 100644 index 0000000..33caa53 --- /dev/null +++ b/node_modules/tinypool/dist/esm/index.js @@ -0,0 +1,818 @@ +"use strict"; +import { + __dirname, + __privateAdd, + __privateGet, + __privateSet, + __publicField, + isMovable, + isTaskQueue, + isTransferable, + kFieldCount, + kQueueOptions, + kRequestCountField, + kResponseCountField, + kTransferable, + kValue, + markMovable +} from "./chunk-QYFJIXNO.js"; + +// src/index.ts +import { + Worker, + MessageChannel, + receiveMessageOnPort +} from "worker_threads"; +import { once } from "events"; + +// src/EventEmitterAsyncResource.ts +import { EventEmitter } from "events"; +import { AsyncResource } from "async_hooks"; +var kEventEmitter = Symbol("kEventEmitter"); +var kAsyncResource = Symbol("kAsyncResource"); +var _a; +var EventEmitterReferencingAsyncResource = class extends AsyncResource { + constructor(ee, type, options) { + super(type, options); + __publicField(this, _a); + this[kEventEmitter] = ee; + } + get eventEmitter() { + return this[kEventEmitter]; + } +}; +_a = kEventEmitter; +var _a2; +var _EventEmitterAsyncResource = class extends EventEmitter { + constructor(options) { + let name; + if (typeof options === "string") { + name = options; + options = void 0; + } else { + name = options?.name || new.target.name; + } + super(options); + __publicField(this, _a2); + this[kAsyncResource] = new EventEmitterReferencingAsyncResource(this, name, options); + } + emit(event, ...args) { + return this.asyncResource.runInAsyncScope(super.emit, this, event, ...args); + } + emitDestroy() { + this.asyncResource.emitDestroy(); + } + asyncId() { + return this.asyncResource.asyncId(); + } + triggerAsyncId() { + return this.asyncResource.triggerAsyncId(); + } + get asyncResource() { + return this[kAsyncResource]; + } + static get EventEmitterAsyncResource() { + return _EventEmitterAsyncResource; + } +}; +var EventEmitterAsyncResource = _EventEmitterAsyncResource; +_a2 = kAsyncResource; +var EventEmitterAsyncResource_default = EventEmitterAsyncResource; + +// src/index.ts +import { AsyncResource as AsyncResource2 } from "async_hooks"; +import { fileURLToPath, URL } from "url"; +import { dirname, join, resolve } from "path"; +import { inspect, types } from "util"; +import assert from "assert"; +import { performance } from "perf_hooks"; +import { readFileSync } from "fs"; + +// src/physicalCpuCount.ts +import os from "os"; +import childProcess from "child_process"; +function exec(command) { + const output = childProcess.execSync(command, { + encoding: "utf8", + stdio: [null, null, null] + }); + return output; +} +var amount; +try { + const platform = os.platform(); + if (platform === "linux") { + const output1 = exec('cat /proc/cpuinfo | grep "physical id" | sort |uniq | wc -l'); + const output2 = exec('cat /proc/cpuinfo | grep "core id" | sort | uniq | wc -l'); + const physicalCpuAmount = parseInt(output1.trim(), 10); + const physicalCoreAmount = parseInt(output2.trim(), 10); + amount = physicalCpuAmount * physicalCoreAmount; + } else if (platform === "darwin") { + const output = exec("sysctl -n hw.physicalcpu_max"); + amount = parseInt(output.trim(), 10); + } else if (platform === "win32") { + throw new Error(); + } else { + const cores = os.cpus().filter(function(cpu, index) { + const hasHyperthreading = cpu.model.includes("Intel"); + const isOdd = index % 2 === 1; + return !hasHyperthreading || isOdd; + }); + amount = cores.length; + } +} catch { + amount = os.cpus().length; +} + +// src/index.ts +var cpuCount = amount; +function onabort(abortSignal, listener) { + if ("addEventListener" in abortSignal) { + abortSignal.addEventListener("abort", listener, { once: true }); + } else { + abortSignal.once("abort", listener); + } +} +var AbortError = class extends Error { + constructor() { + super("The task has been aborted"); + } + get name() { + return "AbortError"; + } +}; +var ArrayTaskQueue = class { + constructor() { + __publicField(this, "tasks", []); + } + get size() { + return this.tasks.length; + } + shift() { + return this.tasks.shift(); + } + push(task) { + this.tasks.push(task); + } + remove(task) { + const index = this.tasks.indexOf(task); + assert.notStrictEqual(index, -1); + this.tasks.splice(index, 1); + } +}; +var kDefaultOptions = { + filename: null, + name: "default", + minThreads: Math.max(cpuCount / 2, 1), + maxThreads: cpuCount, + idleTimeout: 0, + maxQueue: Infinity, + concurrentTasksPerWorker: 1, + useAtomics: true, + taskQueue: new ArrayTaskQueue(), + trackUnmanagedFds: true +}; +var kDefaultRunOptions = { + transferList: void 0, + filename: null, + signal: null, + name: null +}; +var _value; +var DirectlyTransferable = class { + constructor(value) { + __privateAdd(this, _value, void 0); + __privateSet(this, _value, value); + } + get [kTransferable]() { + return __privateGet(this, _value); + } + get [kValue]() { + return __privateGet(this, _value); + } +}; +_value = new WeakMap(); +var _view; +var ArrayBufferViewTransferable = class { + constructor(view) { + __privateAdd(this, _view, void 0); + __privateSet(this, _view, view); + } + get [kTransferable]() { + return __privateGet(this, _view).buffer; + } + get [kValue]() { + return __privateGet(this, _view); + } +}; +_view = new WeakMap(); +var taskIdCounter = 0; +function maybeFileURLToPath(filename) { + return filename.startsWith("file:") ? fileURLToPath(new URL(filename)) : filename; +} +var TaskInfo = class extends AsyncResource2 { + constructor(task, transferList, filename, name, callback, abortSignal, triggerAsyncId) { + super("Tinypool.Task", { requireManualDestroy: true, triggerAsyncId }); + __publicField(this, "callback"); + __publicField(this, "task"); + __publicField(this, "transferList"); + __publicField(this, "filename"); + __publicField(this, "name"); + __publicField(this, "taskId"); + __publicField(this, "abortSignal"); + __publicField(this, "abortListener", null); + __publicField(this, "workerInfo", null); + __publicField(this, "created"); + __publicField(this, "started"); + this.callback = callback; + this.task = task; + this.transferList = transferList; + if (isMovable(task)) { + if (this.transferList == null) { + this.transferList = []; + } + this.transferList = this.transferList.concat(task[kTransferable]); + this.task = task[kValue]; + } + this.filename = filename; + this.name = name; + this.taskId = taskIdCounter++; + this.abortSignal = abortSignal; + this.created = performance.now(); + this.started = 0; + } + releaseTask() { + const ret = this.task; + this.task = null; + return ret; + } + done(err, result) { + this.emitDestroy(); + this.runInAsyncScope(this.callback, null, err, result); + if (this.abortSignal && this.abortListener) { + if ("removeEventListener" in this.abortSignal && this.abortListener) { + this.abortSignal.removeEventListener("abort", this.abortListener); + } else { + ; + this.abortSignal.off("abort", this.abortListener); + } + } + } + get [kQueueOptions]() { + return kQueueOptions in this.task ? this.task[kQueueOptions] : null; + } +}; +var AsynchronouslyCreatedResource = class { + constructor() { + __publicField(this, "onreadyListeners", []); + } + markAsReady() { + const listeners = this.onreadyListeners; + assert(listeners !== null); + this.onreadyListeners = null; + for (const listener of listeners) { + listener(); + } + } + isReady() { + return this.onreadyListeners === null; + } + onReady(fn) { + if (this.onreadyListeners === null) { + fn(); + return; + } + this.onreadyListeners.push(fn); + } +}; +var AsynchronouslyCreatedResourcePool = class { + constructor(maximumUsage) { + __publicField(this, "pendingItems", /* @__PURE__ */ new Set()); + __publicField(this, "readyItems", /* @__PURE__ */ new Set()); + __publicField(this, "maximumUsage"); + __publicField(this, "onAvailableListeners"); + this.maximumUsage = maximumUsage; + this.onAvailableListeners = []; + } + add(item) { + this.pendingItems.add(item); + item.onReady(() => { + if (this.pendingItems.has(item)) { + this.pendingItems.delete(item); + this.readyItems.add(item); + this.maybeAvailable(item); + } + }); + } + delete(item) { + this.pendingItems.delete(item); + this.readyItems.delete(item); + } + findAvailable() { + let minUsage = this.maximumUsage; + let candidate = null; + for (const item of this.readyItems) { + const usage = item.currentUsage(); + if (usage === 0) + return item; + if (usage < minUsage) { + candidate = item; + minUsage = usage; + } + } + return candidate; + } + *[Symbol.iterator]() { + yield* this.pendingItems; + yield* this.readyItems; + } + get size() { + return this.pendingItems.size + this.readyItems.size; + } + maybeAvailable(item) { + if (item.currentUsage() < this.maximumUsage) { + for (const listener of this.onAvailableListeners) { + listener(item); + } + } + } + onAvailable(fn) { + this.onAvailableListeners.push(fn); + } +}; +var Errors = { + ThreadTermination: () => new Error("Terminating worker thread"), + FilenameNotProvided: () => new Error("filename must be provided to run() or in options object"), + TaskQueueAtLimit: () => new Error("Task queue is at limit"), + NoTaskQueueAvailable: () => new Error("No task queue available and all Workers are busy") +}; +var WorkerInfo = class extends AsynchronouslyCreatedResource { + constructor(worker, port, workerId, freeWorkerId, onMessage) { + super(); + __publicField(this, "worker"); + __publicField(this, "workerId"); + __publicField(this, "freeWorkerId"); + __publicField(this, "taskInfos"); + __publicField(this, "idleTimeout", null); + __publicField(this, "port"); + __publicField(this, "sharedBuffer"); + __publicField(this, "lastSeenResponseCount", 0); + __publicField(this, "onMessage"); + this.worker = worker; + this.workerId = workerId; + this.freeWorkerId = freeWorkerId; + this.port = port; + this.port.on("message", (message) => this._handleResponse(message)); + this.onMessage = onMessage; + this.taskInfos = /* @__PURE__ */ new Map(); + this.sharedBuffer = new Int32Array(new SharedArrayBuffer(kFieldCount * Int32Array.BYTES_PER_ELEMENT)); + } + destroy() { + this.worker.terminate(); + this.port.close(); + this.freeWorkerId(); + this.clearIdleTimeout(); + for (const taskInfo of this.taskInfos.values()) { + taskInfo.done(Errors.ThreadTermination()); + } + this.taskInfos.clear(); + } + clearIdleTimeout() { + if (this.idleTimeout !== null) { + clearTimeout(this.idleTimeout); + this.idleTimeout = null; + } + } + ref() { + this.port.ref(); + return this; + } + unref() { + this.port.unref(); + return this; + } + _handleResponse(message) { + this.onMessage(message); + if (this.taskInfos.size === 0) { + this.unref(); + } + } + postTask(taskInfo) { + assert(!this.taskInfos.has(taskInfo.taskId)); + const message = { + task: taskInfo.releaseTask(), + taskId: taskInfo.taskId, + filename: taskInfo.filename, + name: taskInfo.name + }; + try { + this.port.postMessage(message, taskInfo.transferList); + } catch (err) { + taskInfo.done(err); + return; + } + taskInfo.workerInfo = this; + this.taskInfos.set(taskInfo.taskId, taskInfo); + this.ref(); + this.clearIdleTimeout(); + Atomics.add(this.sharedBuffer, kRequestCountField, 1); + Atomics.notify(this.sharedBuffer, kRequestCountField, 1); + } + processPendingMessages() { + const actualResponseCount = Atomics.load(this.sharedBuffer, kResponseCountField); + if (actualResponseCount !== this.lastSeenResponseCount) { + this.lastSeenResponseCount = actualResponseCount; + let entry; + while ((entry = receiveMessageOnPort(this.port)) !== void 0) { + this._handleResponse(entry.message); + } + } + } + isRunningAbortableTask() { + if (this.taskInfos.size !== 1) + return false; + const [[, task]] = this.taskInfos; + return task.abortSignal !== null; + } + currentUsage() { + if (this.isRunningAbortableTask()) + return Infinity; + return this.taskInfos.size; + } +}; +var ThreadPool = class { + constructor(publicInterface, options) { + __publicField(this, "publicInterface"); + __publicField(this, "workers"); + __publicField(this, "workerIds"); + __publicField(this, "options"); + __publicField(this, "taskQueue"); + __publicField(this, "skipQueue", []); + __publicField(this, "completed", 0); + __publicField(this, "start", performance.now()); + __publicField(this, "inProcessPendingMessages", false); + __publicField(this, "startingUp", false); + __publicField(this, "workerFailsDuringBootstrap", false); + this.publicInterface = publicInterface; + this.taskQueue = options.taskQueue || new ArrayTaskQueue(); + const filename = options.filename ? maybeFileURLToPath(options.filename) : null; + this.options = { ...kDefaultOptions, ...options, filename, maxQueue: 0 }; + if (options.maxThreads !== void 0 && this.options.minThreads >= options.maxThreads) { + this.options.minThreads = options.maxThreads; + } + if (options.minThreads !== void 0 && this.options.maxThreads <= options.minThreads) { + this.options.maxThreads = options.minThreads; + } + if (options.maxQueue === "auto") { + this.options.maxQueue = this.options.maxThreads ** 2; + } else { + this.options.maxQueue = options.maxQueue ?? kDefaultOptions.maxQueue; + } + this.workerIds = new Map(new Array(options.maxThreads).fill(0).map((_, i) => [i + 1, true])); + this.workers = new AsynchronouslyCreatedResourcePool(this.options.concurrentTasksPerWorker); + this.workers.onAvailable((w) => this._onWorkerAvailable(w)); + this.startingUp = true; + this._ensureMinimumWorkers(); + this.startingUp = false; + } + _ensureMaximumWorkers() { + while (this.workers.size < this.options.maxThreads) { + this._addNewWorker(); + } + } + _ensureMinimumWorkers() { + while (this.workers.size < this.options.minThreads) { + this._addNewWorker(); + } + } + _addNewWorker() { + const pool = this; + const workerIds = this.workerIds; + const __dirname2 = dirname(fileURLToPath(import.meta.url)); + let workerId; + workerIds.forEach((isIdAvailable, _workerId2) => { + if (isIdAvailable && !workerId) { + workerId = _workerId2; + workerIds.set(_workerId2, false); + } + }); + const tinypoolPrivateData = { workerId }; + const worker = new Worker(resolve(__dirname2, "./worker.js"), { + env: this.options.env, + argv: this.options.argv, + execArgv: this.options.execArgv, + resourceLimits: this.options.resourceLimits, + workerData: [ + tinypoolPrivateData, + this.options.workerData + ], + trackUnmanagedFds: this.options.trackUnmanagedFds + }); + const onMessage = (message2) => { + const { taskId, result } = message2; + const taskInfo = workerInfo.taskInfos.get(taskId); + workerInfo.taskInfos.delete(taskId); + if (!this.options.isolateWorkers) + pool.workers.maybeAvailable(workerInfo); + if (taskInfo === void 0) { + const err = new Error(`Unexpected message from Worker: ${inspect(message2)}`); + pool.publicInterface.emit("error", err); + } else { + taskInfo.done(message2.error, result); + } + pool._processPendingMessages(); + }; + const { port1, port2 } = new MessageChannel(); + const workerInfo = new WorkerInfo(worker, port1, workerId, () => workerIds.set(workerId, true), onMessage); + if (this.startingUp) { + workerInfo.markAsReady(); + } + const message = { + filename: this.options.filename, + name: this.options.name, + port: port2, + sharedBuffer: workerInfo.sharedBuffer, + useAtomics: this.options.useAtomics + }; + worker.postMessage(message, [port2]); + worker.on("message", (message2) => { + if (message2.ready === true) { + if (workerInfo.currentUsage() === 0) { + workerInfo.unref(); + } + if (!workerInfo.isReady()) { + workerInfo.markAsReady(); + } + return; + } + worker.emit("error", new Error(`Unexpected message on Worker: ${inspect(message2)}`)); + }); + worker.on("error", (err) => { + worker.ref = () => { + }; + const taskInfos = [...workerInfo.taskInfos.values()]; + workerInfo.taskInfos.clear(); + this._removeWorker(workerInfo); + if (workerInfo.isReady() && !this.workerFailsDuringBootstrap) { + this._ensureMinimumWorkers(); + } else { + this.workerFailsDuringBootstrap = true; + } + if (taskInfos.length > 0) { + for (const taskInfo of taskInfos) { + taskInfo.done(err, null); + } + } else { + this.publicInterface.emit("error", err); + } + }); + worker.unref(); + port1.on("close", () => { + worker.ref(); + }); + this.workers.add(workerInfo); + } + _processPendingMessages() { + if (this.inProcessPendingMessages || !this.options.useAtomics) { + return; + } + this.inProcessPendingMessages = true; + try { + for (const workerInfo of this.workers) { + workerInfo.processPendingMessages(); + } + } finally { + this.inProcessPendingMessages = false; + } + } + _removeWorker(workerInfo) { + workerInfo.destroy(); + this.workers.delete(workerInfo); + } + _onWorkerAvailable(workerInfo) { + while ((this.taskQueue.size > 0 || this.skipQueue.length > 0) && workerInfo.currentUsage() < this.options.concurrentTasksPerWorker) { + const taskInfo = this.skipQueue.shift() || this.taskQueue.shift(); + if (taskInfo.abortSignal && workerInfo.taskInfos.size > 0) { + this.skipQueue.push(taskInfo); + break; + } + const now = performance.now(); + taskInfo.started = now; + workerInfo.postTask(taskInfo); + this._maybeDrain(); + return; + } + if (workerInfo.taskInfos.size === 0 && this.workers.size > this.options.minThreads) { + workerInfo.idleTimeout = setTimeout(() => { + assert.strictEqual(workerInfo.taskInfos.size, 0); + if (this.workers.size > this.options.minThreads) { + this._removeWorker(workerInfo); + } + }, this.options.idleTimeout).unref(); + } + } + runTask(task, options) { + let { filename, name } = options; + const { transferList = [], signal = null } = options; + if (filename == null) { + filename = this.options.filename; + } + if (name == null) { + name = this.options.name; + } + if (typeof filename !== "string") { + return Promise.reject(Errors.FilenameNotProvided()); + } + filename = maybeFileURLToPath(filename); + let resolve2; + let reject; + const ret = new Promise((res, rej) => { + resolve2 = res; + reject = rej; + }); + const taskInfo = new TaskInfo(task, transferList, filename, name, (err, result) => { + this.completed++; + if (err !== null) { + reject(err); + } else { + resolve2(result); + } + if (this.options.isolateWorkers && taskInfo.workerInfo) { + this._removeWorker(taskInfo.workerInfo); + this._ensureMinimumWorkers(); + } + }, signal, this.publicInterface.asyncResource.asyncId()); + if (signal !== null) { + if (signal.aborted) { + return Promise.reject(new AbortError()); + } + taskInfo.abortListener = () => { + reject(new AbortError()); + if (taskInfo.workerInfo !== null) { + this._removeWorker(taskInfo.workerInfo); + this._ensureMinimumWorkers(); + } else { + this.taskQueue.remove(taskInfo); + } + }; + onabort(signal, taskInfo.abortListener); + } + if (this.taskQueue.size > 0) { + const totalCapacity = this.options.maxQueue + this.pendingCapacity(); + if (this.taskQueue.size >= totalCapacity) { + if (this.options.maxQueue === 0) { + return Promise.reject(Errors.NoTaskQueueAvailable()); + } else { + return Promise.reject(Errors.TaskQueueAtLimit()); + } + } else { + if (this.workers.size < this.options.maxThreads) { + this._addNewWorker(); + } + this.taskQueue.push(taskInfo); + } + return ret; + } + let workerInfo = this.workers.findAvailable(); + if (workerInfo !== null && workerInfo.currentUsage() > 0 && signal) { + workerInfo = null; + } + let waitingForNewWorker = false; + if ((workerInfo === null || workerInfo.currentUsage() > 0) && this.workers.size < this.options.maxThreads) { + this._addNewWorker(); + waitingForNewWorker = true; + } + if (workerInfo === null) { + if (this.options.maxQueue <= 0 && !waitingForNewWorker) { + return Promise.reject(Errors.NoTaskQueueAvailable()); + } else { + this.taskQueue.push(taskInfo); + } + return ret; + } + const now = performance.now(); + taskInfo.started = now; + workerInfo.postTask(taskInfo); + this._maybeDrain(); + return ret; + } + pendingCapacity() { + return this.workers.pendingItems.size * this.options.concurrentTasksPerWorker; + } + _maybeDrain() { + if (this.taskQueue.size === 0 && this.skipQueue.length === 0) { + this.publicInterface.emit("drain"); + } + } + async destroy() { + while (this.skipQueue.length > 0) { + const taskInfo = this.skipQueue.shift(); + taskInfo.done(new Error("Terminating worker thread")); + } + while (this.taskQueue.size > 0) { + const taskInfo = this.taskQueue.shift(); + taskInfo.done(new Error("Terminating worker thread")); + } + const exitEvents = []; + while (this.workers.size > 0) { + const [workerInfo] = this.workers; + exitEvents.push(once(workerInfo.worker, "exit")); + this._removeWorker(workerInfo); + } + await Promise.all(exitEvents); + } +}; +var _pool; +var Tinypool = class extends EventEmitterAsyncResource_default { + constructor(options = {}) { + if (options.minThreads !== void 0 && options.minThreads > 0 && options.minThreads < 1) { + options.minThreads = Math.max(1, Math.floor(options.minThreads * cpuCount)); + } + if (options.maxThreads !== void 0 && options.maxThreads > 0 && options.maxThreads < 1) { + options.maxThreads = Math.max(1, Math.floor(options.maxThreads * cpuCount)); + } + super({ ...options, name: "Tinypool" }); + __privateAdd(this, _pool, void 0); + if (options.minThreads !== void 0 && options.maxThreads !== void 0 && options.minThreads > options.maxThreads) { + throw new RangeError("options.minThreads and options.maxThreads must not conflict"); + } + __privateSet(this, _pool, new ThreadPool(this, options)); + } + run(task, options = kDefaultRunOptions) { + const { transferList, filename, name, signal } = options; + return __privateGet(this, _pool).runTask(task, { transferList, filename, name, signal }); + } + destroy() { + return __privateGet(this, _pool).destroy(); + } + get options() { + return __privateGet(this, _pool).options; + } + get threads() { + const ret = []; + for (const workerInfo of __privateGet(this, _pool).workers) { + ret.push(workerInfo.worker); + } + return ret; + } + get queueSize() { + const pool = __privateGet(this, _pool); + return Math.max(pool.taskQueue.size - pool.pendingCapacity(), 0); + } + get completed() { + return __privateGet(this, _pool).completed; + } + get duration() { + return performance.now() - __privateGet(this, _pool).start; + } + static get isWorkerThread() { + return process.__tinypool_state__?.isWorkerThread || false; + } + static get workerData() { + return process.__tinypool_state__?.workerData || void 0; + } + static get version() { + const { version } = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf-8")); + return version; + } + static move(val) { + if (val != null && typeof val === "object" && typeof val !== "function") { + if (!isTransferable(val)) { + if (types.isArrayBufferView(val)) { + val = new ArrayBufferViewTransferable(val); + } else { + val = new DirectlyTransferable(val); + } + } + markMovable(val); + } + return val; + } + static get transferableSymbol() { + return kTransferable; + } + static get valueSymbol() { + return kValue; + } + static get queueOptionsSymbol() { + return kQueueOptions; + } +}; +_pool = new WeakMap(); +var _workerId = process.__tinypool_state__?.workerId; +var src_default = Tinypool; +export { + Tinypool, + src_default as default, + isMovable, + isTaskQueue, + isTransferable, + kFieldCount, + kQueueOptions, + kRequestCountField, + kResponseCountField, + kTransferable, + kValue, + markMovable, + _workerId as workerId +}; diff --git a/node_modules/tinypool/dist/esm/worker.js b/node_modules/tinypool/dist/esm/worker.js new file mode 100644 index 0000000..bcc6b2f --- /dev/null +++ b/node_modules/tinypool/dist/esm/worker.js @@ -0,0 +1,142 @@ +"use strict"; +import { + isMovable, + kRequestCountField, + kResponseCountField, + kTransferable, + kValue +} from "./chunk-QYFJIXNO.js"; + +// src/worker.ts +import { + parentPort, + receiveMessageOnPort, + workerData as tinypoolData +} from "worker_threads"; +import { pathToFileURL } from "url"; + +// src/utils.ts +function stdout() { + return console._stdout || process.stdout || void 0; +} +function stderr() { + return console._stderr || process.stderr || void 0; +} + +// src/worker.ts +var [tinypoolPrivateData, workerData] = tinypoolData; +process.__tinypool_state__ = { + isWorkerThread: true, + workerData, + workerId: tinypoolPrivateData.workerId +}; +var handlerCache = /* @__PURE__ */ new Map(); +var useAtomics = process.env.PISCINA_DISABLE_ATOMICS !== "1"; +var importESMCached; +function getImportESM() { + if (importESMCached === void 0) { + importESMCached = new Function("specifier", "return import(specifier)"); + } + return importESMCached; +} +async function getHandler(filename, name) { + let handler = handlerCache.get(`${filename}/${name}`); + if (handler !== void 0) { + return handler; + } + try { + const handlerModule = await import(filename); + handler = typeof handlerModule.default !== "function" && handlerModule.default || handlerModule; + if (typeof handler !== "function") { + handler = await handler[name]; + } + } catch { + } + if (typeof handler !== "function") { + handler = await getImportESM()(pathToFileURL(filename).href); + if (typeof handler !== "function") { + handler = await handler[name]; + } + } + if (typeof handler !== "function") { + return null; + } + if (handlerCache.size > 1e3) { + const [[key]] = handlerCache; + handlerCache.delete(key); + } + handlerCache.set(`${filename}/${name}`, handler); + return handler; +} +parentPort.on("message", (message) => { + useAtomics = process.env.PISCINA_DISABLE_ATOMICS === "1" ? false : message.useAtomics; + const { port, sharedBuffer, filename, name } = message; + (async function() { + if (filename !== null) { + await getHandler(filename, name); + } + const readyMessage = { ready: true }; + parentPort.postMessage(readyMessage); + port.on("message", onMessage.bind(null, port, sharedBuffer)); + atomicsWaitLoop(port, sharedBuffer); + })().catch(throwInNextTick); +}); +var currentTasks = 0; +var lastSeenRequestCount = 0; +function atomicsWaitLoop(port, sharedBuffer) { + if (!useAtomics) + return; + while (currentTasks === 0) { + Atomics.wait(sharedBuffer, kRequestCountField, lastSeenRequestCount); + lastSeenRequestCount = Atomics.load(sharedBuffer, kRequestCountField); + let entry; + while ((entry = receiveMessageOnPort(port)) !== void 0) { + onMessage(port, sharedBuffer, entry.message); + } + } +} +function onMessage(port, sharedBuffer, message) { + currentTasks++; + const { taskId, task, filename, name } = message; + (async function() { + let response; + let transferList = []; + try { + const handler = await getHandler(filename, name); + if (handler === null) { + throw new Error(`No handler function exported from ${filename}`); + } + let result = await handler(task); + if (isMovable(result)) { + transferList = transferList.concat(result[kTransferable]); + result = result[kValue]; + } + response = { + taskId, + result, + error: null + }; + if (stdout()?.writableLength > 0) { + await new Promise((resolve) => process.stdout.write("", resolve)); + } + if (stderr()?.writableLength > 0) { + await new Promise((resolve) => process.stderr.write("", resolve)); + } + } catch (error) { + response = { + taskId, + result: null, + error + }; + } + currentTasks--; + port.postMessage(response, transferList); + Atomics.add(sharedBuffer, kResponseCountField, 1); + atomicsWaitLoop(port, sharedBuffer); + })().catch(throwInNextTick); +} +function throwInNextTick(error) { + process.nextTick(() => { + throw error; + }); +} diff --git a/node_modules/tinypool/dist/index.d.ts b/node_modules/tinypool/dist/index.d.ts new file mode 100644 index 0000000..6817bc3 --- /dev/null +++ b/node_modules/tinypool/dist/index.d.ts @@ -0,0 +1,172 @@ +import { MessagePort, Worker } from 'worker_threads'; +import { EventEmitter } from 'events'; +import { AsyncResource } from 'async_hooks'; + +declare const kEventEmitter: unique symbol; +declare const kAsyncResource: unique symbol; +declare type EventEmitterOptions = typeof EventEmitter extends { + new (options?: infer T): EventEmitter; +} ? T : never; +declare type AsyncResourceOptions = typeof AsyncResource extends { + new (name: string, options?: infer T): AsyncResource; +} ? T : never; +declare type Options$1 = EventEmitterOptions & AsyncResourceOptions & { + name?: string; +}; +declare class EventEmitterReferencingAsyncResource extends AsyncResource { + [kEventEmitter]: EventEmitter; + constructor(ee: EventEmitter, type: string, options?: AsyncResourceOptions); + get eventEmitter(): EventEmitter; +} +declare class EventEmitterAsyncResource extends EventEmitter { + [kAsyncResource]: EventEmitterReferencingAsyncResource; + constructor(options?: Options$1 | string); + emit(event: string | symbol, ...args: any[]): boolean; + emitDestroy(): void; + asyncId(): number; + triggerAsyncId(): number; + get asyncResource(): EventEmitterReferencingAsyncResource; + static get EventEmitterAsyncResource(): typeof EventEmitterAsyncResource; +} + +interface StartupMessage { + filename: string | null; + name: string; + port: MessagePort; + sharedBuffer: Int32Array; + useAtomics: boolean; +} +interface RequestMessage { + taskId: number; + task: any; + filename: string; + name: string; +} +interface ReadyMessage { + ready: true; +} +interface ResponseMessage { + taskId: number; + result: any; + error: unknown | null; +} +interface TinypoolPrivateData { + workerId: number; +} +declare type TinypoolData = [TinypoolPrivateData, any]; +declare const kTransferable: unique symbol; +declare const kValue: unique symbol; +declare const kQueueOptions: unique symbol; +declare function isTransferable(value: any): boolean; +declare function isMovable(value: any): boolean; +declare function markMovable(value: object): void; +interface Transferable { + readonly [kTransferable]: object; + readonly [kValue]: object; +} +interface Task { + readonly [kQueueOptions]: object | null; +} +interface TaskQueue { + readonly size: number; + shift(): Task | null; + remove(task: Task): void; + push(task: Task): void; +} +declare function isTaskQueue(value: any): boolean; +declare const kRequestCountField = 0; +declare const kResponseCountField = 1; +declare const kFieldCount = 2; + +declare global { + namespace NodeJS { + interface Process { + __tinypool_state__: { + isWorkerThread: boolean; + workerData: any; + workerId: number; + }; + } + } +} +interface AbortSignalEventTargetAddOptions { + once: boolean; +} +interface AbortSignalEventTarget { + addEventListener: (name: 'abort', listener: () => void, options?: AbortSignalEventTargetAddOptions) => void; + removeEventListener: (name: 'abort', listener: () => void) => void; + aborted?: boolean; +} +interface AbortSignalEventEmitter { + off: (name: 'abort', listener: () => void) => void; + once: (name: 'abort', listener: () => void) => void; +} +declare type AbortSignalAny = AbortSignalEventTarget | AbortSignalEventEmitter; +declare type ResourceLimits = Worker extends { + resourceLimits?: infer T; +} ? T : {}; +declare type EnvSpecifier = typeof Worker extends { + new (filename: never, options?: { + env: infer T; + }): Worker; +} ? T : never; +interface Options { + filename?: string | null; + name?: string; + minThreads?: number; + maxThreads?: number; + idleTimeout?: number; + maxQueue?: number | 'auto'; + concurrentTasksPerWorker?: number; + useAtomics?: boolean; + resourceLimits?: ResourceLimits; + argv?: string[]; + execArgv?: string[]; + env?: EnvSpecifier; + workerData?: any; + taskQueue?: TaskQueue; + trackUnmanagedFds?: boolean; + isolateWorkers?: boolean; +} +interface FilledOptions extends Options { + filename: string | null; + name: string; + minThreads: number; + maxThreads: number; + idleTimeout: number; + maxQueue: number; + concurrentTasksPerWorker: number; + useAtomics: boolean; + taskQueue: TaskQueue; +} +interface RunOptions { + transferList?: TransferList; + filename?: string | null; + signal?: AbortSignalAny | null; + name?: string | null; +} +declare type TransferList = MessagePort extends { + postMessage(value: any, transferList: infer T): any; +} ? T : never; +declare type TransferListItem = TransferList extends (infer T)[] ? T : never; +declare class Tinypool extends EventEmitterAsyncResource { + #private; + constructor(options?: Options); + run(task: any, options?: RunOptions): Promise; + destroy(): Promise; + get options(): FilledOptions; + get threads(): Worker[]; + get queueSize(): number; + get completed(): number; + get duration(): number; + static get isWorkerThread(): boolean; + static get workerData(): any; + static get version(): string; + static move(val: Transferable | TransferListItem | ArrayBufferView | ArrayBuffer | MessagePort): MessagePort | ArrayBuffer | Transferable | ArrayBufferView; + static get transferableSymbol(): symbol; + static get valueSymbol(): symbol; + static get queueOptionsSymbol(): symbol; +} +declare const _workerId: number; + +export { Options, ReadyMessage, RequestMessage, ResponseMessage, StartupMessage, Task, TaskQueue, Tinypool, TinypoolData, TinypoolPrivateData, Transferable, Tinypool as default, isMovable, isTaskQueue, isTransferable, kFieldCount, kQueueOptions, kRequestCountField, kResponseCountField, kTransferable, kValue, markMovable, _workerId as workerId }; diff --git a/node_modules/tinypool/dist/worker.d.ts b/node_modules/tinypool/dist/worker.d.ts new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/node_modules/tinypool/dist/worker.d.ts @@ -0,0 +1 @@ + diff --git a/node_modules/tinypool/package.json b/node_modules/tinypool/package.json new file mode 100644 index 0000000..0a22ec1 --- /dev/null +++ b/node_modules/tinypool/package.json @@ -0,0 +1,29 @@ +{ + "name": "tinypool", + "version": "0.3.0", + "description": "A minimal and tiny Node.js Worker Thread Pool implementation, a fork of piscina, but with fewer features", + "type": "module", + "main": "./dist/esm/index.js", + "module": "./dist/esm/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist/**" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/aslemammad/tinypool.git" + }, + "keywords": [ + "fast", + "worker threads", + "thread pool" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/aslemammad/tinypool/issues" + }, + "homepage": "https://github.com/aslemammad/tinypool#readme", + "engines": { + "node": ">=14.0.0" + } +} diff --git a/node_modules/tinyspy/README.md b/node_modules/tinyspy/README.md new file mode 100644 index 0000000..dc4e8e2 --- /dev/null +++ b/node_modules/tinyspy/README.md @@ -0,0 +1,11 @@ +# tinyspy + +> minimal fork of nanospy, with more features 🕵🏻‍♂️ + +A `9KB` package for minimal and easy testing with no dependencies. +This package was created for having a tiny spy library to use in `vitest`, but it can also be used in `jest` and other test environments. + +_In case you need more tiny libraries like tinypool or tinyspy, please consider submitting an [RFC](https://github.com/tinylibs/rfcs)_ + +## Docs +Read **[full docs](https://github.com/tinylibs/tinyspy#readme)** on GitHub. diff --git a/node_modules/tinyspy/dist/index.cjs b/node_modules/tinyspy/dist/index.cjs new file mode 100644 index 0000000..8bb4d17 --- /dev/null +++ b/node_modules/tinyspy/dist/index.cjs @@ -0,0 +1,122 @@ +"use strict"; +var h = Object.defineProperty; +var O = Object.getOwnPropertyDescriptor; +var P = Object.getOwnPropertyNames; +var K = Object.prototype.hasOwnProperty; +var b = (t, e) => { + for (var n in e) + h(t, n, { get: e[n], enumerable: !0 }); +}, M = (t, e, n, s) => { + if (e && typeof e == "object" || typeof e == "function") + for (let r of P(e)) + !K.call(t, r) && r !== n && h(t, r, { get: () => e[r], enumerable: !(s = O(e, r)) || s.enumerable }); + return t; +}; +var F = (t) => M(h({}, "__esModule", { value: !0 }), t); + +// src/index.ts +var E = {}; +b(E, { + restoreAll: () => C, + spies: () => x, + spy: () => S, + spyOn: () => I +}); +module.exports = F(E); + +// src/utils.ts +function d(t, e) { + if (!t) + throw new Error(e); +} +function y(t, e) { + return typeof e === t; +} +function A(t) { + return t instanceof Promise; +} +function f(t, e, n) { + Object.defineProperty(t, e, n); +} + +// src/spy.ts +var x = /* @__PURE__ */ new Set(); +function S(t) { + d(y("function", t) || y("undefined", t), "cannot spy on a non-function value"); + let e = function(...s) { + if (e.called = !0, e.callCount++, e.calls.push(s), e.next) { + let [i, l] = e.next; + if (e.results.push(e.next), e.next = null, i === "ok") + return l; + throw l; + } + let r, o = "ok"; + if (e.impl) + try { + r = e.impl.apply(this, s), o = "ok"; + } catch (i) { + throw r = i, o = "error", e.results.push([o, i]), i; + } + let c = [o, r]; + if (A(r)) { + let i = r.then((l) => c[1] = l).catch((l) => { + throw c[0] = "error", c[1] = l, l; + }); + Object.assign(i, r), r = i; + } + return e.results.push(c), r; + }; + f(e, "_isMockFunction", { get: () => !0 }), f(e, "length", { value: t ? t.length : 0 }), f(e, "returns", { + get() { + return this.results.map(([, s]) => s); + } + }), f(e, "name", { value: t && t.name || "spy" }); + let n = () => { + e.called = !1, e.callCount = 0, e.results = [], e.calls = []; + }; + return n(), e.impl = t, e.reset = n, e.nextError = (s) => (e.next = ["error", s], e), e.nextResult = (s) => (e.next = ["ok", s], e), e; +} + +// src/spyOn.ts +var k = (t, e) => Object.getOwnPropertyDescriptor(t, e); +function I(t, e, n) { + d(!y("undefined", t), "spyOn could not find an object to spy upon"), d(y("object", t) || y("function", t), "cannot spyOn on a primitive value"); + let s = () => { + if (typeof e != "object") + return [e, "value"]; + if ("getter" in e && "setter" in e) + throw new Error("cannot spy on both getter and setter"); + if ("getter" in e) + return [e.getter, "get"]; + if ("setter" in e) + return [e.setter, "set"]; + throw new Error("specify getter or setter to spy on"); + }, [r, o] = s(), c = k(t, r), i = Object.getPrototypeOf(t), l = i && k(i, r), a = c || l; + d(a || r in t, `${String(r)} does not exist`); + let R = !1; + o === "value" && a && !a.value && a.get && (o = "get", R = !0, n = a.get()); + let u; + a ? u = a[o] : o !== "value" ? u = () => t[r] : u = t[r], n || (n = u); + let p = S(n), v = (T) => { + let { value: G, ...m } = a || { + configurable: !0, + writable: !0 + }; + o !== "value" && delete m.writable, m[o] = T, f(t, r, m); + }, w = () => v(u); + return p.restore = w, p.getOriginal = () => R ? u() : u, p.willCall = (T) => (p.impl = T, p), v(R ? () => p : p), x.add(p), p; +} + +// src/restoreAll.ts +function C() { + for (let t of x) + t.restore(); + x.clear(); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + restoreAll, + spies, + spy, + spyOn +}); diff --git a/node_modules/tinyspy/dist/index.d.ts b/node_modules/tinyspy/dist/index.d.ts new file mode 100644 index 0000000..536a15c --- /dev/null +++ b/node_modules/tinyspy/dist/index.d.ts @@ -0,0 +1,49 @@ +declare let spies: Set>; +declare type ReturnError = ['error', any]; +declare type ReturnOk = ['ok', R]; +declare type ResultFn = ReturnError | ReturnOk; +interface Spy { + called: boolean; + callCount: number; + calls: A[]; + length: number; + results: ResultFn[]; + returns: R[]; + nextError(error: any): this; + nextResult(result: R): this; + reset(): void; + impl: ((...args: A) => R) | undefined; + next: ResultFn | null; +} +interface SpyImpl extends Spy { + getOriginal(): (...args: A) => R; + willCall(cb: (...args: A) => R): this; + restore(): void; +} +interface SpyFn extends Spy { + (...args: A): R; +} +declare function spy(cb?: (...args: A) => R): SpyFn; + +declare type Procedure = (...args: any[]) => any; +declare type Methods = { + [K in keyof T]: T[K] extends Procedure ? K : never; +}[keyof T]; +declare type Getters = { + [K in keyof T]: T[K] extends Procedure ? never : K; +}[keyof T]; +declare type Classes = { + [K in keyof T]: T[K] extends new (...args: any[]) => any ? K : never; +}[keyof T]; +declare function spyOn>>(obj: T, methodName: { + setter: S; +}, mock?: (arg: T[S]) => void): SpyImpl<[T[S]], void>; +declare function spyOn>>(obj: T, methodName: { + getter: G; +}, mock?: () => T[G]): SpyImpl<[], T[G]>; +declare function spyOn>>(object: T, method: M): Required[M] extends new (...args: infer A) => infer R ? SpyImpl : never; +declare function spyOn>>(obj: T, methodName: M, mock?: T[M]): Required[M] extends (...args: infer A) => infer R ? SpyImpl : never; + +declare function restoreAll(): void; + +export { Spy, SpyFn, SpyImpl, restoreAll, spies, spy, spyOn }; diff --git a/node_modules/tinyspy/dist/index.js b/node_modules/tinyspy/dist/index.js new file mode 100644 index 0000000..7275810 --- /dev/null +++ b/node_modules/tinyspy/dist/index.js @@ -0,0 +1,95 @@ +// src/utils.ts +function d(t, e) { + if (!t) + throw new Error(e); +} +function y(t, e) { + return typeof e === t; +} +function v(t) { + return t instanceof Promise; +} +function f(t, e, i) { + Object.defineProperty(t, e, i); +} + +// src/spy.ts +var x = /* @__PURE__ */ new Set(); +function A(t) { + d(y("function", t) || y("undefined", t), "cannot spy on a non-function value"); + let e = function(...o) { + if (e.called = !0, e.callCount++, e.calls.push(o), e.next) { + let [s, l] = e.next; + if (e.results.push(e.next), e.next = null, s === "ok") + return l; + throw l; + } + let r, n = "ok"; + if (e.impl) + try { + r = e.impl.apply(this, o), n = "ok"; + } catch (s) { + throw r = s, n = "error", e.results.push([n, s]), s; + } + let c = [n, r]; + if (v(r)) { + let s = r.then((l) => c[1] = l).catch((l) => { + throw c[0] = "error", c[1] = l, l; + }); + Object.assign(s, r), r = s; + } + return e.results.push(c), r; + }; + f(e, "_isMockFunction", { get: () => !0 }), f(e, "length", { value: t ? t.length : 0 }), f(e, "returns", { + get() { + return this.results.map(([, o]) => o); + } + }), f(e, "name", { value: t && t.name || "spy" }); + let i = () => { + e.called = !1, e.callCount = 0, e.results = [], e.calls = []; + }; + return i(), e.impl = t, e.reset = i, e.nextError = (o) => (e.next = ["error", o], e), e.nextResult = (o) => (e.next = ["ok", o], e), e; +} + +// src/spyOn.ts +var k = (t, e) => Object.getOwnPropertyDescriptor(t, e); +function C(t, e, i) { + d(!y("undefined", t), "spyOn could not find an object to spy upon"), d(y("object", t) || y("function", t), "cannot spyOn on a primitive value"); + let o = () => { + if (typeof e != "object") + return [e, "value"]; + if ("getter" in e && "setter" in e) + throw new Error("cannot spy on both getter and setter"); + if ("getter" in e) + return [e.getter, "get"]; + if ("setter" in e) + return [e.setter, "set"]; + throw new Error("specify getter or setter to spy on"); + }, [r, n] = o(), c = k(t, r), s = Object.getPrototypeOf(t), l = s && k(s, r), a = c || l; + d(a || r in t, `${String(r)} does not exist`); + let T = !1; + n === "value" && a && !a.value && a.get && (n = "get", T = !0, i = a.get()); + let u; + a ? u = a[n] : n !== "value" ? u = () => t[r] : u = t[r], i || (i = u); + let p = A(i), S = (m) => { + let { value: O, ...h } = a || { + configurable: !0, + writable: !0 + }; + n !== "value" && delete h.writable, h[n] = m, f(t, r, h); + }, w = () => S(u); + return p.restore = w, p.getOriginal = () => T ? u() : u, p.willCall = (m) => (p.impl = m, p), S(T ? () => p : p), x.add(p), p; +} + +// src/restoreAll.ts +function q() { + for (let t of x) + t.restore(); + x.clear(); +} +export { + q as restoreAll, + x as spies, + A as spy, + C as spyOn +}; diff --git a/node_modules/tinyspy/package.json b/node_modules/tinyspy/package.json new file mode 100644 index 0000000..22bc776 --- /dev/null +++ b/node_modules/tinyspy/package.json @@ -0,0 +1,38 @@ +{ + "name": "tinyspy", + "version": "1.0.2", + "type": "module", + "main": "./dist/index.cjs", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js", + "require": "./dist/index.cjs", + "default": "./dist/index.cjs" + }, + "files": [ + "dist/**" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/tinylibs/tinyspy.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/tinylibs/tinyspy/issues" + }, + "homepage": "https://github.com/tinylibs/tinyspy#readme", + "keywords": [ + "spy", + "mock", + "typescript", + "method" + ], + "engines": { + "node": ">=14.0.0" + }, + "scripts": { + "publish": "npm run build && clean-publish" + } +} diff --git a/node_modules/to-regex-range/LICENSE b/node_modules/to-regex-range/LICENSE new file mode 100644 index 0000000..7cccaf9 --- /dev/null +++ b/node_modules/to-regex-range/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-present, Jon Schlinkert. + +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/to-regex-range/README.md b/node_modules/to-regex-range/README.md new file mode 100644 index 0000000..38887da --- /dev/null +++ b/node_modules/to-regex-range/README.md @@ -0,0 +1,305 @@ +# to-regex-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/to-regex-range.svg?style=flat)](https://www.npmjs.com/package/to-regex-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![NPM total downloads](https://img.shields.io/npm/dt/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![Linux Build Status](https://img.shields.io/travis/micromatch/to-regex-range.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/to-regex-range) + +> Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save to-regex-range +``` + +
+What does this do? + +
+ +This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. + +**Example** + +```js +const toRegexRange = require('to-regex-range'); +const regex = new RegExp(toRegexRange('15', '95')); +``` + +A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string). + +
+ +
+ +
+Why use this library? + +
+ +### Convenience + +Creating regular expressions for matching numbers gets deceptively complicated pretty fast. + +For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: + +* regex for matching `1` => `/1/` (easy enough) +* regex for matching `1` through `5` => `/[1-5]/` (not bad...) +* regex for matching `1` or `5` => `/(1|5)/` (still easy...) +* regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) +* regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) +* regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) +* regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) + +The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. + +**Learn more** + +If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. + +### Heavily tested + +As of April 07, 2019, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct. + +Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7. + +### Optimized + +Generated regular expressions are optimized: + +* duplicate sequences and character classes are reduced using quantifiers +* smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative +* uses fragment caching to avoid processing the same exact string more than once + +
+ +
+ +## Usage + +Add this library to your javascript application with the following line of code + +```js +const toRegexRange = require('to-regex-range'); +``` + +The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). + +```js +const source = toRegexRange('15', '95'); +//=> 1[5-9]|[2-8][0-9]|9[0-5] + +const regex = new RegExp(`^${source}$`); +console.log(regex.test('14')); //=> false +console.log(regex.test('50')); //=> true +console.log(regex.test('94')); //=> true +console.log(regex.test('96')); //=> false +``` + +## Options + +### options.capture + +**Type**: `boolean` + +**Deafault**: `undefined` + +Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. + +```js +console.log(toRegexRange('-10', '10')); +//=> -[1-9]|-?10|[0-9] + +console.log(toRegexRange('-10', '10', { capture: true })); +//=> (-[1-9]|-?10|[0-9]) +``` + +### options.shorthand + +**Type**: `boolean` + +**Deafault**: `undefined` + +Use the regex shorthand for `[0-9]`: + +```js +console.log(toRegexRange('0', '999999')); +//=> [0-9]|[1-9][0-9]{1,5} + +console.log(toRegexRange('0', '999999', { shorthand: true })); +//=> \d|[1-9]\d{1,5} +``` + +### options.relaxZeros + +**Type**: `boolean` + +**Default**: `true` + +This option relaxes matching for leading zeros when when ranges are zero-padded. + +```js +const source = toRegexRange('-0010', '0010'); +const regex = new RegExp(`^${source}$`); +console.log(regex.test('-10')); //=> true +console.log(regex.test('-010')); //=> true +console.log(regex.test('-0010')); //=> true +console.log(regex.test('10')); //=> true +console.log(regex.test('010')); //=> true +console.log(regex.test('0010')); //=> true +``` + +When `relaxZeros` is false, matching is strict: + +```js +const source = toRegexRange('-0010', '0010', { relaxZeros: false }); +const regex = new RegExp(`^${source}$`); +console.log(regex.test('-10')); //=> false +console.log(regex.test('-010')); //=> false +console.log(regex.test('-0010')); //=> true +console.log(regex.test('10')); //=> false +console.log(regex.test('010')); //=> false +console.log(regex.test('0010')); //=> true +``` + +## Examples + +| **Range** | **Result** | **Compile time** | +| --- | --- | --- | +| `toRegexRange(-10, 10)` | `-[1-9]\|-?10\|[0-9]` | _132μs_ | +| `toRegexRange(-100, -10)` | `-1[0-9]\|-[2-9][0-9]\|-100` | _50μs_ | +| `toRegexRange(-100, 100)` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _42μs_ | +| `toRegexRange(001, 100)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|100` | _109μs_ | +| `toRegexRange(001, 555)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _51μs_ | +| `toRegexRange(0010, 1000)` | `0{0,2}1[0-9]\|0{0,2}[2-9][0-9]\|0?[1-9][0-9]{2}\|1000` | _31μs_ | +| `toRegexRange(1, 50)` | `[1-9]\|[1-4][0-9]\|50` | _24μs_ | +| `toRegexRange(1, 55)` | `[1-9]\|[1-4][0-9]\|5[0-5]` | _23μs_ | +| `toRegexRange(1, 555)` | `[1-9]\|[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _30μs_ | +| `toRegexRange(1, 5555)` | `[1-9]\|[1-9][0-9]{1,2}\|[1-4][0-9]{3}\|5[0-4][0-9]{2}\|55[0-4][0-9]\|555[0-5]` | _43μs_ | +| `toRegexRange(111, 555)` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _38μs_ | +| `toRegexRange(29, 51)` | `29\|[34][0-9]\|5[01]` | _24μs_ | +| `toRegexRange(31, 877)` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _32μs_ | +| `toRegexRange(5, 5)` | `5` | _8μs_ | +| `toRegexRange(5, 6)` | `5\|6` | _11μs_ | +| `toRegexRange(1, 2)` | `1\|2` | _6μs_ | +| `toRegexRange(1, 5)` | `[1-5]` | _15μs_ | +| `toRegexRange(1, 10)` | `[1-9]\|10` | _22μs_ | +| `toRegexRange(1, 100)` | `[1-9]\|[1-9][0-9]\|100` | _25μs_ | +| `toRegexRange(1, 1000)` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _31μs_ | +| `toRegexRange(1, 10000)` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _34μs_ | +| `toRegexRange(1, 100000)` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _36μs_ | +| `toRegexRange(1, 1000000)` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _42μs_ | +| `toRegexRange(1, 10000000)` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _42μs_ | + +## Heads up! + +**Order of arguments** + +When the `min` is larger than the `max`, values will be flipped to create a valid range: + +```js +toRegexRange('51', '29'); +``` + +Is effectively flipped to: + +```js +toRegexRange('29', '51'); +//=> 29|[3-4][0-9]|5[0-1] +``` + +**Steps / increments** + +This library does not support steps (increments). A pr to add support would be welcome. + +## History + +### v2.0.0 - 2017-04-21 + +**New features** + +Adds support for zero-padding! + +### v1.0.0 + +**Optimizations** + +Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. + +## Attribution + +Inspired by the python library [range-regex](https://github.com/dimka665/range-regex). + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by micromatch.") +* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") +* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") +* [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") +* [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 63 | [jonschlinkert](https://github.com/jonschlinkert) | +| 3 | [doowb](https://github.com/doowb) | +| 2 | [realityking](https://github.com/realityking) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! + +
+ + + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 07, 2019._ \ No newline at end of file diff --git a/node_modules/to-regex-range/index.js b/node_modules/to-regex-range/index.js new file mode 100644 index 0000000..77fbace --- /dev/null +++ b/node_modules/to-regex-range/index.js @@ -0,0 +1,288 @@ +/*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + +'use strict'; + +const isNumber = require('is-number'); + +const toRegexRange = (min, max, options) => { + if (isNumber(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange.cache.hasOwnProperty(cacheKey)) { + return toRegexRange.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives, opts); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; + let onlyPositive = filterPatterns(pos, neg, '', false, options) || []; + let intersected = filterPatterns(neg, pos, '-?', true, options) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit, options); + + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { pattern, count: [count], digits }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { string } = ele; + + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } + + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} + +/** + * Zip strings + */ + +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} + +/** + * Cache + */ + +toRegexRange.cache = {}; +toRegexRange.clearCache = () => (toRegexRange.cache = {}); + +/** + * Expose `toRegexRange` + */ + +module.exports = toRegexRange; diff --git a/node_modules/to-regex-range/package.json b/node_modules/to-regex-range/package.json new file mode 100644 index 0000000..4ef194f --- /dev/null +++ b/node_modules/to-regex-range/package.json @@ -0,0 +1,88 @@ +{ + "name": "to-regex-range", + "description": "Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions.", + "version": "5.0.1", + "homepage": "https://github.com/micromatch/to-regex-range", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Rouven Weßling (www.rouvenwessling.de)" + ], + "repository": "micromatch/to-regex-range", + "bugs": { + "url": "https://github.com/micromatch/to-regex-range/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=8.0" + }, + "scripts": { + "test": "mocha" + }, + "dependencies": { + "is-number": "^7.0.0" + }, + "devDependencies": { + "fill-range": "^6.0.0", + "gulp-format-md": "^2.0.0", + "mocha": "^6.0.2", + "text-table": "^0.2.0", + "time-diff": "^0.3.1" + }, + "keywords": [ + "bash", + "date", + "expand", + "expansion", + "expression", + "glob", + "match", + "match date", + "match number", + "match numbers", + "match year", + "matches", + "matching", + "number", + "numbers", + "numerical", + "range", + "ranges", + "regex", + "regexp", + "regular", + "regular expression", + "sequence" + ], + "verb": { + "layout": "default", + "toc": false, + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "helpers": { + "examples": { + "displayName": "examples" + } + }, + "related": { + "list": [ + "expand-range", + "fill-range", + "micromatch", + "repeat-element", + "repeat-string" + ] + } + } +} diff --git a/node_modules/type-detect/LICENSE b/node_modules/type-detect/LICENSE new file mode 100644 index 0000000..7ea799f --- /dev/null +++ b/node_modules/type-detect/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Jake Luer (http://alogicalparadox.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/type-detect/README.md b/node_modules/type-detect/README.md new file mode 100644 index 0000000..d2c4cb7 --- /dev/null +++ b/node_modules/type-detect/README.md @@ -0,0 +1,228 @@ +

+ + ChaiJS type-detect + +

+
+

+ Improved typeof detection for node and the browser. +

+ +

+ + license:mit + + + tag:? + + + build:? + + + coverage:? + + + npm:? + + + dependencies:? + + + devDependencies:? + +
+ + + + + + + + + + + + + + +
Supported Browsers
Chrome Edge Firefox Safari IE
9, 10, 11
+
+ + Join the Slack chat + + + Join the Gitter chat + +

+ +## What is Type-Detect? + +Type Detect is a module which you can use to detect the type of a given object. It returns a string representation of the object's type, either using [`typeof`](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-typeof-operator) or [`@@toStringTag`](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-symbol.tostringtag). It also normalizes some object names for consistency among browsers. + +## Why? + +The `typeof` operator will only specify primitive values; everything else is `"object"` (including `null`, arrays, regexps, etc). Many developers use `Object.prototype.toString()` - which is a fine alternative and returns many more types (null returns `[object Null]`, Arrays as `[object Array]`, regexps as `[object RegExp]` etc). + +Sadly, `Object.prototype.toString` is slow, and buggy. By slow - we mean it is slower than `typeof`. By buggy - we mean that some values (like Promises, the global object, iterators, dataviews, a bunch of HTML elements) all report different things in different browsers. + +`type-detect` fixes all of the shortcomings with `Object.prototype.toString`. We have extra code to speed up checks of JS and DOM objects, as much as 20-30x faster for some values. `type-detect` also fixes any consistencies with these objects. + +## Installation + +### Node.js + +`type-detect` is available on [npm](http://npmjs.org). To install it, type: + + $ npm install type-detect + +### Browsers + +You can also use it within the browser; install via npm and use the `type-detect.js` file found within the download. For example: + +```html + +``` + +## Usage + +The primary export of `type-detect` is function that can serve as a replacement for `typeof`. The results of this function will be more specific than that of native `typeof`. + +```js +var type = require('type-detect'); +``` + +#### array + +```js +assert(type([]) === 'Array'); +assert(type(new Array()) === 'Array'); +``` + +#### regexp + +```js +assert(type(/a-z/gi) === 'RegExp'); +assert(type(new RegExp('a-z')) === 'RegExp'); +``` + +#### function + +```js +assert(type(function () {}) === 'function'); +``` + +#### arguments + +```js +(function () { + assert(type(arguments) === 'Arguments'); +})(); +``` + +#### date + +```js +assert(type(new Date) === 'Date'); +``` + +#### number + +```js +assert(type(1) === 'number'); +assert(type(1.234) === 'number'); +assert(type(-1) === 'number'); +assert(type(-1.234) === 'number'); +assert(type(Infinity) === 'number'); +assert(type(NaN) === 'number'); +assert(type(new Number(1)) === 'Number'); // note - the object version has a capital N +``` + +#### string + +```js +assert(type('hello world') === 'string'); +assert(type(new String('hello')) === 'String'); // note - the object version has a capital S +``` + +#### null + +```js +assert(type(null) === 'null'); +assert(type(undefined) !== 'null'); +``` + +#### undefined + +```js +assert(type(undefined) === 'undefined'); +assert(type(null) !== 'undefined'); +``` + +#### object + +```js +var Noop = function () {}; +assert(type({}) === 'Object'); +assert(type(Noop) !== 'Object'); +assert(type(new Noop) === 'Object'); +assert(type(new Object) === 'Object'); +``` + +#### ECMA6 Types + +All new ECMAScript 2015 objects are also supported, such as Promises and Symbols: + +```js +assert(type(new Map() === 'Map'); +assert(type(new WeakMap()) === 'WeakMap'); +assert(type(new Set()) === 'Set'); +assert(type(new WeakSet()) === 'WeakSet'); +assert(type(Symbol()) === 'symbol'); +assert(type(new Promise(callback) === 'Promise'); +assert(type(new Int8Array()) === 'Int8Array'); +assert(type(new Uint8Array()) === 'Uint8Array'); +assert(type(new UInt8ClampedArray()) === 'Uint8ClampedArray'); +assert(type(new Int16Array()) === 'Int16Array'); +assert(type(new Uint16Array()) === 'Uint16Array'); +assert(type(new Int32Array()) === 'Int32Array'); +assert(type(new UInt32Array()) === 'Uint32Array'); +assert(type(new Float32Array()) === 'Float32Array'); +assert(type(new Float64Array()) === 'Float64Array'); +assert(type(new ArrayBuffer()) === 'ArrayBuffer'); +assert(type(new DataView(arrayBuffer)) === 'DataView'); +``` + +Also, if you use `Symbol.toStringTag` to change an Objects return value of the `toString()` Method, `type()` will return this value, e.g: + +```js +var myObject = {}; +myObject[Symbol.toStringTag] = 'myCustomType'; +assert(type(myObject) === 'myCustomType'); +``` diff --git a/node_modules/type-detect/index.js b/node_modules/type-detect/index.js new file mode 100644 index 0000000..98a1e03 --- /dev/null +++ b/node_modules/type-detect/index.js @@ -0,0 +1,378 @@ +/* ! + * type-detect + * Copyright(c) 2013 jake luer + * MIT Licensed + */ +const promiseExists = typeof Promise === 'function'; + +/* eslint-disable no-undef */ +const globalObject = typeof self === 'object' ? self : global; // eslint-disable-line id-blacklist + +const symbolExists = typeof Symbol !== 'undefined'; +const mapExists = typeof Map !== 'undefined'; +const setExists = typeof Set !== 'undefined'; +const weakMapExists = typeof WeakMap !== 'undefined'; +const weakSetExists = typeof WeakSet !== 'undefined'; +const dataViewExists = typeof DataView !== 'undefined'; +const symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined'; +const symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined'; +const setEntriesExists = setExists && typeof Set.prototype.entries === 'function'; +const mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function'; +const setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries()); +const mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries()); +const arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function'; +const arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]()); +const stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function'; +const stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]()); +const toStringLeftSliceLength = 8; +const toStringRightSliceLength = -1; +/** + * ### typeOf (obj) + * + * Uses `Object.prototype.toString` to determine the type of an object, + * normalising behaviour across engine versions & well optimised. + * + * @param {Mixed} object + * @return {String} object type + * @api public + */ +export default function typeDetect(obj) { + /* ! Speed optimisation + * Pre: + * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled) + * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled) + * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled) + * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled) + * function x 2,556,769 ops/sec ±1.73% (77 runs sampled) + * Post: + * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled) + * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled) + * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled) + * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled) + * function x 31,296,870 ops/sec ±0.96% (83 runs sampled) + */ + const typeofObj = typeof obj; + if (typeofObj !== 'object') { + return typeofObj; + } + + /* ! Speed optimisation + * Pre: + * null x 28,645,765 ops/sec ±1.17% (82 runs sampled) + * Post: + * null x 36,428,962 ops/sec ±1.37% (84 runs sampled) + */ + if (obj === null) { + return 'null'; + } + + /* ! Spec Conformance + * Test: `Object.prototype.toString.call(window)`` + * - Node === "[object global]" + * - Chrome === "[object global]" + * - Firefox === "[object Window]" + * - PhantomJS === "[object Window]" + * - Safari === "[object Window]" + * - IE 11 === "[object Window]" + * - IE Edge === "[object Window]" + * Test: `Object.prototype.toString.call(this)`` + * - Chrome Worker === "[object global]" + * - Firefox Worker === "[object DedicatedWorkerGlobalScope]" + * - Safari Worker === "[object DedicatedWorkerGlobalScope]" + * - IE 11 Worker === "[object WorkerGlobalScope]" + * - IE Edge Worker === "[object WorkerGlobalScope]" + */ + if (obj === globalObject) { + return 'global'; + } + + /* ! Speed optimisation + * Pre: + * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled) + * Post: + * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled) + */ + if ( + Array.isArray(obj) && + (symbolToStringTagExists === false || !(Symbol.toStringTag in obj)) + ) { + return 'Array'; + } + + // Not caching existence of `window` and related properties due to potential + // for `window` to be unset before tests in quasi-browser environments. + if (typeof window === 'object' && window !== null) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/browsers.html#location) + * WhatWG HTML$7.7.3 - The `Location` interface + * Test: `Object.prototype.toString.call(window.location)`` + * - IE <=11 === "[object Object]" + * - IE Edge <=13 === "[object Object]" + */ + if (typeof window.location === 'object' && obj === window.location) { + return 'Location'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#document) + * WhatWG HTML$3.1.1 - The `Document` object + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * WhatWG HTML states: + * > For historical reasons, Window objects must also have a + * > writable, configurable, non-enumerable property named + * > HTMLDocument whose value is the Document interface object. + * Test: `Object.prototype.toString.call(document)`` + * - Chrome === "[object HTMLDocument]" + * - Firefox === "[object HTMLDocument]" + * - Safari === "[object HTMLDocument]" + * - IE <=10 === "[object Document]" + * - IE 11 === "[object HTMLDocument]" + * - IE Edge <=13 === "[object HTMLDocument]" + */ + if (typeof window.document === 'object' && obj === window.document) { + return 'Document'; + } + + if (typeof window.navigator === 'object') { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray + * Test: `Object.prototype.toString.call(navigator.mimeTypes)`` + * - IE <=10 === "[object MSMimeTypesCollection]" + */ + if (typeof window.navigator.mimeTypes === 'object' && + obj === window.navigator.mimeTypes) { + return 'MimeTypeArray'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray + * Test: `Object.prototype.toString.call(navigator.plugins)`` + * - IE <=10 === "[object MSPluginsCollection]" + */ + if (typeof window.navigator.plugins === 'object' && + obj === window.navigator.plugins) { + return 'PluginArray'; + } + } + + if ((typeof window.HTMLElement === 'function' || + typeof window.HTMLElement === 'object') && + obj instanceof window.HTMLElement) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement` + * Test: `Object.prototype.toString.call(document.createElement('blockquote'))`` + * - IE <=10 === "[object HTMLBlockElement]" + */ + if (obj.tagName === 'BLOCKQUOTE') { + return 'HTMLQuoteElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltabledatacellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('td')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TD') { + return 'HTMLTableDataCellElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltableheadercellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('th')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TH') { + return 'HTMLTableHeaderCellElement'; + } + } + } + + /* ! Speed optimisation + * Pre: + * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled) + * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled) + * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled) + * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled) + * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled) + * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled) + * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled) + * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled) + * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled) + * Post: + * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled) + * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled) + * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled) + * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled) + * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled) + * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled) + * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled) + * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled) + * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled) + */ + const stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]); + if (typeof stringTag === 'string') { + return stringTag; + } + + const objPrototype = Object.getPrototypeOf(obj); + /* ! Speed optimisation + * Pre: + * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled) + * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled) + * Post: + * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled) + * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled) + */ + if (objPrototype === RegExp.prototype) { + return 'RegExp'; + } + + /* ! Speed optimisation + * Pre: + * date x 2,130,074 ops/sec ±4.42% (68 runs sampled) + * Post: + * date x 3,953,779 ops/sec ±1.35% (77 runs sampled) + */ + if (objPrototype === Date.prototype) { + return 'Date'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag) + * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise": + * Test: `Object.prototype.toString.call(Promise.resolve())`` + * - Chrome <=47 === "[object Object]" + * - Edge <=20 === "[object Object]" + * - Firefox 29-Latest === "[object Promise]" + * - Safari 7.1-Latest === "[object Promise]" + */ + if (promiseExists && objPrototype === Promise.prototype) { + return 'Promise'; + } + + /* ! Speed optimisation + * Pre: + * set x 2,222,186 ops/sec ±1.31% (82 runs sampled) + * Post: + * set x 4,545,879 ops/sec ±1.13% (83 runs sampled) + */ + if (setExists && objPrototype === Set.prototype) { + return 'Set'; + } + + /* ! Speed optimisation + * Pre: + * map x 2,396,842 ops/sec ±1.59% (81 runs sampled) + * Post: + * map x 4,183,945 ops/sec ±6.59% (82 runs sampled) + */ + if (mapExists && objPrototype === Map.prototype) { + return 'Map'; + } + + /* ! Speed optimisation + * Pre: + * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled) + * Post: + * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled) + */ + if (weakSetExists && objPrototype === WeakSet.prototype) { + return 'WeakSet'; + } + + /* ! Speed optimisation + * Pre: + * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled) + * Post: + * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled) + */ + if (weakMapExists && objPrototype === WeakMap.prototype) { + return 'WeakMap'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag) + * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView": + * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))`` + * - Edge <=13 === "[object Object]" + */ + if (dataViewExists && objPrototype === DataView.prototype) { + return 'DataView'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag) + * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator": + * Test: `Object.prototype.toString.call(new Map().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (mapExists && objPrototype === mapIteratorPrototype) { + return 'Map Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag) + * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator": + * Test: `Object.prototype.toString.call(new Set().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (setExists && objPrototype === setIteratorPrototype) { + return 'Set Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag) + * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator": + * Test: `Object.prototype.toString.call([][Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) { + return 'Array Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag) + * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator": + * Test: `Object.prototype.toString.call(''[Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (stringIteratorExists && objPrototype === stringIteratorPrototype) { + return 'String Iterator'; + } + + /* ! Speed optimisation + * Pre: + * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled) + * Post: + * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled) + */ + if (objPrototype === null) { + return 'Object'; + } + + return Object + .prototype + .toString + .call(obj) + .slice(toStringLeftSliceLength, toStringRightSliceLength); +} diff --git a/node_modules/type-detect/package.json b/node_modules/type-detect/package.json new file mode 100644 index 0000000..bebf2d8 --- /dev/null +++ b/node_modules/type-detect/package.json @@ -0,0 +1 @@ +{"name":"type-detect","description":"Improved typeof detection for node.js and the browser.","keywords":["type","typeof","types"],"license":"MIT","author":"Jake Luer (http://alogicalparadox.com)","contributors":["Keith Cirkel (https://github.com/keithamus)","David Losert (https://github.com/davelosert)","Aleksey Shvayka (https://github.com/shvaikalesh)","Lucas Fernandes da Costa (https://github.com/lucasfcosta)","Grant Snodgrass (https://github.com/meeber)","Jeremy Tice (https://github.com/jetpacmonkey)","Edward Betts (https://github.com/EdwardBetts)","dvlsg (https://github.com/dvlsg)","Amila Welihinda (https://github.com/amilajack)","Jake Champion (https://github.com/JakeChampion)","Miroslav Bajtoš (https://github.com/bajtos)"],"files":["index.js","type-detect.js"],"main":"./type-detect.js","repository":{"type":"git","url":"git+ssh://git@github.com/chaijs/type-detect.git"},"scripts":{"bench":"node bench","build":"rollup -c rollup.conf.js","commit-msg":"commitlint -x angular","lint":"eslint --ignore-path .gitignore .","prepare":"cross-env NODE_ENV=production npm run build","semantic-release":"semantic-release pre && npm publish && semantic-release post","pretest:node":"cross-env NODE_ENV=test npm run build","pretest:browser":"cross-env NODE_ENV=test npm run build","test":"npm run test:node && npm run test:browser","test:browser":"karma start --singleRun=true","test:node":"nyc mocha type-detect.test.js","posttest:node":"nyc report --report-dir \"coverage/node-$(node --version)\" --reporter=lcovonly && npm run upload-coverage","posttest:browser":"npm run upload-coverage","upload-coverage":"codecov"},"eslintConfig":{"env":{"es6":true},"extends":["strict/es6"],"globals":{"HTMLElement":false},"rules":{"complexity":0,"max-statements":0,"prefer-rest-params":0}},"devDependencies":{"@commitlint/cli":"^4.2.2","benchmark":"^2.1.0","buble":"^0.16.0","codecov":"^3.0.0","commitlint-config-angular":"^4.2.1","cross-env":"^5.1.1","eslint":"^4.10.0","eslint-config-strict":"^14.0.0","eslint-plugin-filenames":"^1.2.0","husky":"^0.14.3","karma":"^1.7.1","karma-chrome-launcher":"^2.2.0","karma-coverage":"^1.1.1","karma-detect-browsers":"^2.2.5","karma-edge-launcher":"^0.4.2","karma-firefox-launcher":"^1.0.1","karma-ie-launcher":"^1.0.0","karma-mocha":"^1.3.0","karma-opera-launcher":"^1.0.0","karma-safari-launcher":"^1.0.0","karma-safaritechpreview-launcher":"0.0.6","karma-sauce-launcher":"^1.2.0","mocha":"^4.0.1","nyc":"^11.3.0","rollup":"^0.50.0","rollup-plugin-buble":"^0.16.0","rollup-plugin-commonjs":"^8.2.6","rollup-plugin-istanbul":"^1.1.0","rollup-plugin-node-resolve":"^3.0.0","semantic-release":"^8.2.0","simple-assert":"^1.0.0"},"engines":{"node":">=4"},"version":"4.0.8"} diff --git a/node_modules/type-detect/type-detect.js b/node_modules/type-detect/type-detect.js new file mode 100644 index 0000000..2f55525 --- /dev/null +++ b/node_modules/type-detect/type-detect.js @@ -0,0 +1,388 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.typeDetect = factory()); +}(this, (function () { 'use strict'; + +/* ! + * type-detect + * Copyright(c) 2013 jake luer + * MIT Licensed + */ +var promiseExists = typeof Promise === 'function'; + +/* eslint-disable no-undef */ +var globalObject = typeof self === 'object' ? self : global; // eslint-disable-line id-blacklist + +var symbolExists = typeof Symbol !== 'undefined'; +var mapExists = typeof Map !== 'undefined'; +var setExists = typeof Set !== 'undefined'; +var weakMapExists = typeof WeakMap !== 'undefined'; +var weakSetExists = typeof WeakSet !== 'undefined'; +var dataViewExists = typeof DataView !== 'undefined'; +var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined'; +var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined'; +var setEntriesExists = setExists && typeof Set.prototype.entries === 'function'; +var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function'; +var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries()); +var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries()); +var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function'; +var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]()); +var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function'; +var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]()); +var toStringLeftSliceLength = 8; +var toStringRightSliceLength = -1; +/** + * ### typeOf (obj) + * + * Uses `Object.prototype.toString` to determine the type of an object, + * normalising behaviour across engine versions & well optimised. + * + * @param {Mixed} object + * @return {String} object type + * @api public + */ +function typeDetect(obj) { + /* ! Speed optimisation + * Pre: + * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled) + * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled) + * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled) + * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled) + * function x 2,556,769 ops/sec ±1.73% (77 runs sampled) + * Post: + * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled) + * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled) + * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled) + * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled) + * function x 31,296,870 ops/sec ±0.96% (83 runs sampled) + */ + var typeofObj = typeof obj; + if (typeofObj !== 'object') { + return typeofObj; + } + + /* ! Speed optimisation + * Pre: + * null x 28,645,765 ops/sec ±1.17% (82 runs sampled) + * Post: + * null x 36,428,962 ops/sec ±1.37% (84 runs sampled) + */ + if (obj === null) { + return 'null'; + } + + /* ! Spec Conformance + * Test: `Object.prototype.toString.call(window)`` + * - Node === "[object global]" + * - Chrome === "[object global]" + * - Firefox === "[object Window]" + * - PhantomJS === "[object Window]" + * - Safari === "[object Window]" + * - IE 11 === "[object Window]" + * - IE Edge === "[object Window]" + * Test: `Object.prototype.toString.call(this)`` + * - Chrome Worker === "[object global]" + * - Firefox Worker === "[object DedicatedWorkerGlobalScope]" + * - Safari Worker === "[object DedicatedWorkerGlobalScope]" + * - IE 11 Worker === "[object WorkerGlobalScope]" + * - IE Edge Worker === "[object WorkerGlobalScope]" + */ + if (obj === globalObject) { + return 'global'; + } + + /* ! Speed optimisation + * Pre: + * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled) + * Post: + * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled) + */ + if ( + Array.isArray(obj) && + (symbolToStringTagExists === false || !(Symbol.toStringTag in obj)) + ) { + return 'Array'; + } + + // Not caching existence of `window` and related properties due to potential + // for `window` to be unset before tests in quasi-browser environments. + if (typeof window === 'object' && window !== null) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/browsers.html#location) + * WhatWG HTML$7.7.3 - The `Location` interface + * Test: `Object.prototype.toString.call(window.location)`` + * - IE <=11 === "[object Object]" + * - IE Edge <=13 === "[object Object]" + */ + if (typeof window.location === 'object' && obj === window.location) { + return 'Location'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#document) + * WhatWG HTML$3.1.1 - The `Document` object + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * WhatWG HTML states: + * > For historical reasons, Window objects must also have a + * > writable, configurable, non-enumerable property named + * > HTMLDocument whose value is the Document interface object. + * Test: `Object.prototype.toString.call(document)`` + * - Chrome === "[object HTMLDocument]" + * - Firefox === "[object HTMLDocument]" + * - Safari === "[object HTMLDocument]" + * - IE <=10 === "[object Document]" + * - IE 11 === "[object HTMLDocument]" + * - IE Edge <=13 === "[object HTMLDocument]" + */ + if (typeof window.document === 'object' && obj === window.document) { + return 'Document'; + } + + if (typeof window.navigator === 'object') { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray + * Test: `Object.prototype.toString.call(navigator.mimeTypes)`` + * - IE <=10 === "[object MSMimeTypesCollection]" + */ + if (typeof window.navigator.mimeTypes === 'object' && + obj === window.navigator.mimeTypes) { + return 'MimeTypeArray'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray + * Test: `Object.prototype.toString.call(navigator.plugins)`` + * - IE <=10 === "[object MSPluginsCollection]" + */ + if (typeof window.navigator.plugins === 'object' && + obj === window.navigator.plugins) { + return 'PluginArray'; + } + } + + if ((typeof window.HTMLElement === 'function' || + typeof window.HTMLElement === 'object') && + obj instanceof window.HTMLElement) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement` + * Test: `Object.prototype.toString.call(document.createElement('blockquote'))`` + * - IE <=10 === "[object HTMLBlockElement]" + */ + if (obj.tagName === 'BLOCKQUOTE') { + return 'HTMLQuoteElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltabledatacellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('td')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TD') { + return 'HTMLTableDataCellElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltableheadercellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('th')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TH') { + return 'HTMLTableHeaderCellElement'; + } + } + } + + /* ! Speed optimisation + * Pre: + * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled) + * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled) + * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled) + * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled) + * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled) + * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled) + * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled) + * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled) + * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled) + * Post: + * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled) + * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled) + * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled) + * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled) + * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled) + * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled) + * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled) + * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled) + * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled) + */ + var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]); + if (typeof stringTag === 'string') { + return stringTag; + } + + var objPrototype = Object.getPrototypeOf(obj); + /* ! Speed optimisation + * Pre: + * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled) + * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled) + * Post: + * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled) + * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled) + */ + if (objPrototype === RegExp.prototype) { + return 'RegExp'; + } + + /* ! Speed optimisation + * Pre: + * date x 2,130,074 ops/sec ±4.42% (68 runs sampled) + * Post: + * date x 3,953,779 ops/sec ±1.35% (77 runs sampled) + */ + if (objPrototype === Date.prototype) { + return 'Date'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag) + * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise": + * Test: `Object.prototype.toString.call(Promise.resolve())`` + * - Chrome <=47 === "[object Object]" + * - Edge <=20 === "[object Object]" + * - Firefox 29-Latest === "[object Promise]" + * - Safari 7.1-Latest === "[object Promise]" + */ + if (promiseExists && objPrototype === Promise.prototype) { + return 'Promise'; + } + + /* ! Speed optimisation + * Pre: + * set x 2,222,186 ops/sec ±1.31% (82 runs sampled) + * Post: + * set x 4,545,879 ops/sec ±1.13% (83 runs sampled) + */ + if (setExists && objPrototype === Set.prototype) { + return 'Set'; + } + + /* ! Speed optimisation + * Pre: + * map x 2,396,842 ops/sec ±1.59% (81 runs sampled) + * Post: + * map x 4,183,945 ops/sec ±6.59% (82 runs sampled) + */ + if (mapExists && objPrototype === Map.prototype) { + return 'Map'; + } + + /* ! Speed optimisation + * Pre: + * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled) + * Post: + * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled) + */ + if (weakSetExists && objPrototype === WeakSet.prototype) { + return 'WeakSet'; + } + + /* ! Speed optimisation + * Pre: + * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled) + * Post: + * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled) + */ + if (weakMapExists && objPrototype === WeakMap.prototype) { + return 'WeakMap'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag) + * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView": + * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))`` + * - Edge <=13 === "[object Object]" + */ + if (dataViewExists && objPrototype === DataView.prototype) { + return 'DataView'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag) + * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator": + * Test: `Object.prototype.toString.call(new Map().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (mapExists && objPrototype === mapIteratorPrototype) { + return 'Map Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag) + * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator": + * Test: `Object.prototype.toString.call(new Set().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (setExists && objPrototype === setIteratorPrototype) { + return 'Set Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag) + * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator": + * Test: `Object.prototype.toString.call([][Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) { + return 'Array Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag) + * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator": + * Test: `Object.prototype.toString.call(''[Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (stringIteratorExists && objPrototype === stringIteratorPrototype) { + return 'String Iterator'; + } + + /* ! Speed optimisation + * Pre: + * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled) + * Post: + * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled) + */ + if (objPrototype === null) { + return 'Object'; + } + + return Object + .prototype + .toString + .call(obj) + .slice(toStringLeftSliceLength, toStringRightSliceLength); +} + +return typeDetect; + +}))); diff --git a/node_modules/ufo/LICENSE b/node_modules/ufo/LICENSE new file mode 100644 index 0000000..e739abc --- /dev/null +++ b/node_modules/ufo/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Pooya Parsa + +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/ufo/README.md b/node_modules/ufo/README.md new file mode 100644 index 0000000..5e12ec8 --- /dev/null +++ b/node_modules/ufo/README.md @@ -0,0 +1,234 @@ +[![npm version][npm-version-src]][npm-version-href] +[![npm downloads][npm-downloads-src]][npm-downloads-href] +[![Github Actions][github-actions-src]][github-actions-href] +[![Codecov][codecov-src]][codecov-href] +[![bundle][bundle-src]][bundle-href] + +![👽 ufo](.github/banner.svg) + +## Install + +Install using npm or yarn: + +```bash +npm i ufo +# or +yarn add ufo +``` + +Import: + +```js +// CommonJS +const { normalizeURL, joinURL } = require('ufo') + +// ESM +import { normalizeURL, joinURL } from 'ufo' + +// Deno +import { parseURL } from 'https://unpkg.com/ufo/dist/index.mjs' +``` + +**Notice:** You may need to transpile package and add URL polyfill for legacy environments + +## Usage + +### `normalizeURL` + +- Ensures URL is properly encoded +- Ensures pathname starts with slash +- Preserves protocol/host if provided + +```ts + +// Result: test?query=123%20123#hash,%20test +normalizeURL('test?query=123 123#hash, test') + +// Result: http://localhost:3000/ +normalizeURL('http://localhost:3000') +``` + +### `joinURL` + +```ts +// Result: a/b/c +joinURL('a', '/b', '/c') +``` + +### `resolveURL` + +```ts +// Result: http://foo.com/foo/bar/baz?test=123#token +resolveURL('http://foo.com/foo?test=123#token', 'bar', 'baz') +``` + +### `parseURL` + +```ts +// Result: { protocol: 'http:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' } +parseURL('http://foo.com/foo?test=123#token') + +// Result: { pathname: 'foo.com/foo', search: '?test=123', hash: '#token' } +parseURL('foo.com/foo?test=123#token') + +// Result: { protocol: 'https:', auth: '', host: 'foo.com', pathname: '/foo', search: '?test=123', hash: '#token' } +parseURL('foo.com/foo?test=123#token', 'https://') +``` + +### `withQuery` + +```ts +// Result: /foo?page=a&token=secret +withQuery('/foo?page=a', { token: 'secret' }) +``` + +### `getQuery` + +```ts +// Result: { test: '123', unicode: '好' } +getQuery('http://foo.com/foo?test=123&unicode=%E5%A5%BD') +``` + +### `$URL` + +Implementing URL interface with some improvements: + +- Supporting schemeless and hostless URLs +- Supporting relative URLs +- Preserving trailing-slash status +- Decoded and mutable classs properties (`protocol`, `host`, `auth`, `pathname`, `query`, `hash`) +- Consistent URL parser independent of environment +- Consistent encoding independent of environment +- Punycode support for host encoding + +### `withTrailingSlash` + +Ensures url ends with a trailing slash + +```ts +// Result: /foo/ +withTrailingSlash('/foo') +``` + +```ts +// Result: /path/?query=true +withTrailingSlash('/path?query=true', true) +``` + +### `withoutTrailingSlash` + +Ensures url does not ends with a trailing slash + +```ts +// Result: /foo +withoutTrailingSlash('/foo/') +``` + +```ts +// Result: /path?query=true +withoutTrailingSlash('/path/?query=true', true) +``` + +### `cleanDoubleSlashes` + +Ensures url does not have double slash (except for protocol) + +```ts +// Result: /foo/bar/ +cleanDoubleSlashes('//foo//bar//') +// Result: http://example.com/analyze/http://localhost:3000/ +cleanDoubleSlashes('http://example.com/analyze//http://localhost:3000//') +``` + +### `isSamePath` + +Check two paths are equal or not. Trailing slash and encoding are normalized before comparation. + +```ts +// Result: true +isSamePath('/foo', '/foo/') +``` + +### `isRelative` + +Check if a path starts with `./` or `../`. + +```ts +// Result: true +isRelative('./foo') +``` + +### `withHttp` + +Ensures url protocol is `http` + +```ts +// Result: http://example.com +withHttp('https://example.com') +``` + +### `withHttps` + +Ensures url protocol is `https` + +```ts +// Result: https://example.com +withHttps('http://example.com') +``` + +### `withProtocol` + +Changes url protocol passed as second argument + +```ts +// Result: ftp://example.com +withProtocol('http://example.com', 'ftp://') +``` + +### `withoutProtocol` + +Removes url protocol + +```ts +// Result: example.com +withoutProtocol('http://example.com') +``` + +### `isEqual` + +Compare two URLs regardless of their slash condition or encoding: + +```ts +// Result: true +isEqual('/foo', 'foo') +isEqual('foo/', 'foo') +isEqual('/foo bar', '/foo%20bar') + +// Strict compare +// Result: false +isEqual('/foo', 'foo', { leadingSlash: true }) +isEqual('foo/', 'foo', { trailingSlash: true }) +isEqual('/foo bar', '/foo%20bar', { encoding: true }) +``` + +## License + +[MIT](./LICENSE) + +Special thanks to Eduardo San Martin Morote ([posva](https://github.com/posva)) for [encoding utlities](https://github.com/vuejs/vue-router-next/blob/v4.0.1/src/encoding.ts) + + +[npm-version-src]: https://img.shields.io/npm/v/ufo?style=flat-square +[npm-version-href]: https://npmjs.com/package/ufo + +[npm-downloads-src]: https://img.shields.io/npm/dm/ufo?style=flat-square +[npm-downloads-href]: https://npmjs.com/package/ufo + +[github-actions-src]: https://img.shields.io/github/workflow/status/unjs/ufo/ci/main?style=flat-square +[github-actions-href]: https://github.com/unjs/ufo/actions?query=workflow%3Aci + +[codecov-src]: https://img.shields.io/codecov/c/gh/unjs/ufo/main?style=flat-square +[codecov-href]: https://codecov.io/gh/unjs/ufo + +[bundle-src]: https://img.shields.io/bundlephobia/minzip/ufo?style=flat-square +[bundle-href]: https://bundlephobia.com/result?p=ufo diff --git a/node_modules/ufo/dist/index.cjs b/node_modules/ufo/dist/index.cjs new file mode 100644 index 0000000..59cb8db --- /dev/null +++ b/node_modules/ufo/dist/index.cjs @@ -0,0 +1,499 @@ +'use strict'; + +const n = /[^\0-\x7E]/; +const t = /[\x2E\u3002\uFF0E\uFF61]/g; +const o = { overflow: "Overflow Error", "not-basic": "Illegal Input", "invalid-input": "Invalid Input" }; +const e = Math.floor; +const r = String.fromCharCode; +function s(n2) { + throw new RangeError(o[n2]); +} +const c = function(n2, t2) { + return n2 + 22 + 75 * (n2 < 26) - ((t2 != 0) << 5); +}; +const u = function(n2, t2, o2) { + let r2 = 0; + for (n2 = o2 ? e(n2 / 700) : n2 >> 1, n2 += e(n2 / t2); n2 > 455; r2 += 36) { + n2 = e(n2 / 35); + } + return e(r2 + 36 * n2 / (n2 + 38)); +}; +function toASCII(o2) { + return function(n2, o3) { + const e2 = n2.split("@"); + let r2 = ""; + e2.length > 1 && (r2 = e2[0] + "@", n2 = e2[1]); + const s2 = function(n3, t2) { + const o4 = []; + let e3 = n3.length; + for (; e3--; ) { + o4[e3] = t2(n3[e3]); + } + return o4; + }((n2 = n2.replace(t, ".")).split("."), o3).join("."); + return r2 + s2; + }(o2, function(t2) { + return n.test(t2) ? "xn--" + function(n2) { + const t3 = []; + const o3 = (n2 = function(n3) { + const t4 = []; + let o4 = 0; + const e2 = n3.length; + for (; o4 < e2; ) { + const r2 = n3.charCodeAt(o4++); + if (r2 >= 55296 && r2 <= 56319 && o4 < e2) { + const e3 = n3.charCodeAt(o4++); + (64512 & e3) == 56320 ? t4.push(((1023 & r2) << 10) + (1023 & e3) + 65536) : (t4.push(r2), o4--); + } else { + t4.push(r2); + } + } + return t4; + }(n2)).length; + let f = 128; + let i = 0; + let l = 72; + for (const o4 of n2) { + o4 < 128 && t3.push(r(o4)); + } + const h = t3.length; + let p = h; + for (h && t3.push("-"); p < o3; ) { + let o4 = 2147483647; + for (const t4 of n2) { + t4 >= f && t4 < o4 && (o4 = t4); + } + const a = p + 1; + o4 - f > e((2147483647 - i) / a) && s("overflow"), i += (o4 - f) * a, f = o4; + for (const o5 of n2) { + if (o5 < f && ++i > 2147483647 && s("overflow"), o5 == f) { + let n3 = i; + for (let o6 = 36; ; o6 += 36) { + const s2 = o6 <= l ? 1 : o6 >= l + 26 ? 26 : o6 - l; + if (n3 < s2) { + break; + } + const u2 = n3 - s2; + const f2 = 36 - s2; + t3.push(r(c(s2 + u2 % f2, 0))), n3 = e(u2 / f2); + } + t3.push(r(c(n3, 0))), l = u(i, a, p == h), i = 0, ++p; + } + } + ++i, ++f; + } + return t3.join(""); + }(t2) : t2; + }); +} + +const HASH_RE = /#/g; +const AMPERSAND_RE = /&/g; +const SLASH_RE = /\//g; +const EQUAL_RE = /=/g; +const IM_RE = /\?/g; +const PLUS_RE = /\+/g; +const ENC_BRACKET_OPEN_RE = /%5b/gi; +const ENC_BRACKET_CLOSE_RE = /%5d/gi; +const ENC_CARET_RE = /%5e/gi; +const ENC_BACKTICK_RE = /%60/gi; +const ENC_CURLY_OPEN_RE = /%7b/gi; +const ENC_PIPE_RE = /%7c/gi; +const ENC_CURLY_CLOSE_RE = /%7d/gi; +const ENC_SPACE_RE = /%20/gi; +const ENC_SLASH_RE = /%2f/gi; +const ENC_ENC_SLASH_RE = /%252f/gi; +function encode(text) { + return encodeURI("" + text).replace(ENC_PIPE_RE, "|").replace(ENC_BRACKET_OPEN_RE, "[").replace(ENC_BRACKET_CLOSE_RE, "]"); +} +function encodeHash(text) { + return encode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^"); +} +function encodeQueryValue(text) { + return encode(text).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^"); +} +function encodeQueryKey(text) { + return encodeQueryValue(text).replace(EQUAL_RE, "%3D"); +} +function encodePath(text) { + return encode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F").replace(ENC_ENC_SLASH_RE, "%2F").replace(AMPERSAND_RE, "%26").replace(PLUS_RE, "%2B"); +} +function encodeParam(text) { + return encodePath(text).replace(SLASH_RE, "%2F"); +} +function decode(text = "") { + try { + return decodeURIComponent("" + text); + } catch { + return "" + text; + } +} +function decodePath(text) { + return decode(text.replace(ENC_SLASH_RE, "%252F")); +} +function decodeQueryValue(text) { + return decode(text.replace(PLUS_RE, " ")); +} +function encodeHost(name = "") { + return toASCII(name); +} + +function parseQuery(parametersString = "") { + const object = {}; + if (parametersString[0] === "?") { + parametersString = parametersString.slice(1); + } + for (const parameter of parametersString.split("&")) { + const s = parameter.match(/([^=]+)=?(.*)/) || []; + if (s.length < 2) { + continue; + } + const key = decode(s[1]); + if (key === "__proto__" || key === "constructor") { + continue; + } + const value = decodeQueryValue(s[2] || ""); + if (typeof object[key] !== "undefined") { + if (Array.isArray(object[key])) { + object[key].push(value); + } else { + object[key] = [object[key], value]; + } + } else { + object[key] = value; + } + } + return object; +} +function encodeQueryItem(key, value) { + if (typeof value === "number" || typeof value === "boolean") { + value = String(value); + } + if (!value) { + return encodeQueryKey(key); + } + if (Array.isArray(value)) { + return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&"); + } + return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`; +} +function stringifyQuery(query) { + return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).join("&"); +} + +class $URL { + constructor(input = "") { + this.query = {}; + if (typeof input !== "string") { + throw new TypeError(`URL input should be string received ${typeof input} (${input})`); + } + const parsed = parseURL(input); + this.protocol = decode(parsed.protocol); + this.host = decode(parsed.host); + this.auth = decode(parsed.auth); + this.pathname = decodePath(parsed.pathname); + this.query = parseQuery(parsed.search); + this.hash = decode(parsed.hash); + } + get hostname() { + return parseHost(this.host).hostname; + } + get port() { + return parseHost(this.host).port || ""; + } + get username() { + return parseAuth(this.auth).username; + } + get password() { + return parseAuth(this.auth).password || ""; + } + get hasProtocol() { + return this.protocol.length; + } + get isAbsolute() { + return this.hasProtocol || this.pathname[0] === "/"; + } + get search() { + const q = stringifyQuery(this.query); + return q.length > 0 ? "?" + q : ""; + } + get searchParams() { + const p = new URLSearchParams(); + for (const name in this.query) { + const value = this.query[name]; + if (Array.isArray(value)) { + for (const v of value) { + p.append(name, v); + } + } else { + p.append(name, value || ""); + } + } + return p; + } + get origin() { + return (this.protocol ? this.protocol + "//" : "") + encodeHost(this.host); + } + get fullpath() { + return encodePath(this.pathname) + this.search + encodeHash(this.hash); + } + get encodedAuth() { + if (!this.auth) { + return ""; + } + const { username, password } = parseAuth(this.auth); + return encodeURIComponent(username) + (password ? ":" + encodeURIComponent(password) : ""); + } + get href() { + const auth = this.encodedAuth; + const originWithAuth = (this.protocol ? this.protocol + "//" : "") + (auth ? auth + "@" : "") + encodeHost(this.host); + return this.hasProtocol && this.isAbsolute ? originWithAuth + this.fullpath : this.fullpath; + } + append(url) { + if (url.hasProtocol) { + throw new Error("Cannot append a URL with protocol"); + } + Object.assign(this.query, url.query); + if (url.pathname) { + this.pathname = withTrailingSlash(this.pathname) + withoutLeadingSlash(url.pathname); + } + if (url.hash) { + this.hash = url.hash; + } + } + toJSON() { + return this.href; + } + toString() { + return this.href; + } +} + +function isRelative(inputString) { + return ["./", "../"].some((string_) => inputString.startsWith(string_)); +} +const PROTOCOL_REGEX = /^\w{2,}:(\/\/)?/; +const PROTOCOL_RELATIVE_REGEX = /^\/\/[^/]+/; +function hasProtocol(inputString, acceptProtocolRelative = false) { + return PROTOCOL_REGEX.test(inputString) || acceptProtocolRelative && PROTOCOL_RELATIVE_REGEX.test(inputString); +} +const TRAILING_SLASH_RE = /\/$|\/\?/; +function hasTrailingSlash(input = "", queryParameters = false) { + if (!queryParameters) { + return input.endsWith("/"); + } + return TRAILING_SLASH_RE.test(input); +} +function withoutTrailingSlash(input = "", queryParameters = false) { + if (!queryParameters) { + return (hasTrailingSlash(input) ? input.slice(0, -1) : input) || "/"; + } + if (!hasTrailingSlash(input, true)) { + return input || "/"; + } + const [s0, ...s] = input.split("?"); + return (s0.slice(0, -1) || "/") + (s.length > 0 ? `?${s.join("?")}` : ""); +} +function withTrailingSlash(input = "", queryParameters = false) { + if (!queryParameters) { + return input.endsWith("/") ? input : input + "/"; + } + if (hasTrailingSlash(input, true)) { + return input || "/"; + } + const [s0, ...s] = input.split("?"); + return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : ""); +} +function hasLeadingSlash(input = "") { + return input.startsWith("/"); +} +function withoutLeadingSlash(input = "") { + return (hasLeadingSlash(input) ? input.slice(1) : input) || "/"; +} +function withLeadingSlash(input = "") { + return hasLeadingSlash(input) ? input : "/" + input; +} +function cleanDoubleSlashes(input = "") { + return input.split("://").map((string_) => string_.replace(/\/{2,}/g, "/")).join("://"); +} +function withBase(input, base) { + if (isEmptyURL(base) || hasProtocol(input)) { + return input; + } + const _base = withoutTrailingSlash(base); + if (input.startsWith(_base)) { + return input; + } + return joinURL(_base, input); +} +function withoutBase(input, base) { + if (isEmptyURL(base)) { + return input; + } + const _base = withoutTrailingSlash(base); + if (!input.startsWith(_base)) { + return input; + } + const trimmed = input.slice(_base.length); + return trimmed[0] === "/" ? trimmed : "/" + trimmed; +} +function withQuery(input, query) { + const parsed = parseURL(input); + const mergedQuery = { ...parseQuery(parsed.search), ...query }; + parsed.search = stringifyQuery(mergedQuery); + return stringifyParsedURL(parsed); +} +function getQuery(input) { + return parseQuery(parseURL(input).search); +} +function isEmptyURL(url) { + return !url || url === "/"; +} +function isNonEmptyURL(url) { + return url && url !== "/"; +} +function joinURL(base, ...input) { + let url = base || ""; + for (const index of input.filter((url2) => isNonEmptyURL(url2))) { + url = url ? withTrailingSlash(url) + withoutLeadingSlash(index) : index; + } + return url; +} +function withHttp(input) { + return withProtocol(input, "http://"); +} +function withHttps(input) { + return withProtocol(input, "https://"); +} +function withoutProtocol(input) { + return withProtocol(input, ""); +} +function withProtocol(input, protocol) { + const match = input.match(PROTOCOL_REGEX); + if (!match) { + return protocol + input; + } + return protocol + input.slice(match[0].length); +} +function createURL(input) { + return new $URL(input); +} +function normalizeURL(input) { + return createURL(input).toString(); +} +function resolveURL(base, ...input) { + const url = createURL(base); + for (const index of input.filter((url2) => isNonEmptyURL(url2))) { + url.append(createURL(index)); + } + return url.toString(); +} +function isSamePath(p1, p2) { + return decode(withoutTrailingSlash(p1)) === decode(withoutTrailingSlash(p2)); +} +function isEqual(a, b, options = {}) { + if (!options.trailingSlash) { + a = withTrailingSlash(a); + b = withTrailingSlash(b); + } + if (!options.leadingSlash) { + a = withLeadingSlash(a); + b = withLeadingSlash(b); + } + if (!options.encoding) { + a = decode(a); + b = decode(b); + } + return a === b; +} + +function parseURL(input = "", defaultProto) { + if (!hasProtocol(input, true)) { + return defaultProto ? parseURL(defaultProto + input) : parsePath(input); + } + const [protocol = "", auth, hostAndPath = ""] = (input.replace(/\\/g, "/").match(/([^/:]+:)?\/\/([^/@]+@)?(.*)/) || []).splice(1); + const [host = "", path = ""] = (hostAndPath.match(/([^#/?]*)(.*)?/) || []).splice(1); + const { pathname, search, hash } = parsePath(path.replace(/\/(?=[A-Za-z]:)/, "")); + return { + protocol, + auth: auth ? auth.slice(0, Math.max(0, auth.length - 1)) : "", + host, + pathname, + search, + hash + }; +} +function parsePath(input = "") { + const [pathname = "", search = "", hash = ""] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1); + return { + pathname, + search, + hash + }; +} +function parseAuth(input = "") { + const [username, password] = input.split(":"); + return { + username: decode(username), + password: decode(password) + }; +} +function parseHost(input = "") { + const [hostname, port] = (input.match(/([^/]*)(:0-9+)?/) || []).splice(1); + return { + hostname: decode(hostname), + port + }; +} +function stringifyParsedURL(parsed) { + const fullpath = parsed.pathname + (parsed.search ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search : "") + parsed.hash; + if (!parsed.protocol) { + return fullpath; + } + return parsed.protocol + "//" + (parsed.auth ? parsed.auth + "@" : "") + parsed.host + fullpath; +} + +exports.$URL = $URL; +exports.cleanDoubleSlashes = cleanDoubleSlashes; +exports.createURL = createURL; +exports.decode = decode; +exports.decodePath = decodePath; +exports.decodeQueryValue = decodeQueryValue; +exports.encode = encode; +exports.encodeHash = encodeHash; +exports.encodeHost = encodeHost; +exports.encodeParam = encodeParam; +exports.encodePath = encodePath; +exports.encodeQueryItem = encodeQueryItem; +exports.encodeQueryKey = encodeQueryKey; +exports.encodeQueryValue = encodeQueryValue; +exports.getQuery = getQuery; +exports.hasLeadingSlash = hasLeadingSlash; +exports.hasProtocol = hasProtocol; +exports.hasTrailingSlash = hasTrailingSlash; +exports.isEmptyURL = isEmptyURL; +exports.isEqual = isEqual; +exports.isNonEmptyURL = isNonEmptyURL; +exports.isRelative = isRelative; +exports.isSamePath = isSamePath; +exports.joinURL = joinURL; +exports.normalizeURL = normalizeURL; +exports.parseAuth = parseAuth; +exports.parseHost = parseHost; +exports.parsePath = parsePath; +exports.parseQuery = parseQuery; +exports.parseURL = parseURL; +exports.resolveURL = resolveURL; +exports.stringifyParsedURL = stringifyParsedURL; +exports.stringifyQuery = stringifyQuery; +exports.withBase = withBase; +exports.withHttp = withHttp; +exports.withHttps = withHttps; +exports.withLeadingSlash = withLeadingSlash; +exports.withProtocol = withProtocol; +exports.withQuery = withQuery; +exports.withTrailingSlash = withTrailingSlash; +exports.withoutBase = withoutBase; +exports.withoutLeadingSlash = withoutLeadingSlash; +exports.withoutProtocol = withoutProtocol; +exports.withoutTrailingSlash = withoutTrailingSlash; diff --git a/node_modules/ufo/dist/index.d.ts b/node_modules/ufo/dist/index.d.ts new file mode 100644 index 0000000..ba58aff --- /dev/null +++ b/node_modules/ufo/dist/index.d.ts @@ -0,0 +1,155 @@ +/** + * Encode characters that need to be encoded on the path, search and hash + * sections of the URL. + * + * @internal + * @param text - string to encode + * @returns encoded string + */ +declare function encode(text: string | number): string; +/** + * Encode characters that need to be encoded on the hash section of the URL. + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodeHash(text: string): string; +/** + * Encode characters that need to be encoded query values on the query + * section of the URL. + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodeQueryValue(text: string | number): string; +/** + * Like `encodeQueryValue` but also encodes the `=` character. + * + * @param text - string to encode + */ +declare function encodeQueryKey(text: string | number): string; +/** + * Encode characters that need to be encoded on the path section of the URL. + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodePath(text: string | number): string; +/** + * Encode characters that need to be encoded on the path section of the URL as a + * param. This function encodes everything {@link encodePath} does plus the + * slash (`/`) character. + * + * @param text - string to encode + * @returns encoded string + */ +declare function encodeParam(text: string | number): string; +/** + * Decode text using `decodeURIComponent`. Returns the original text if it + * fails. + * + * @param text - string to decode + * @returns decoded string + */ +declare function decode(text?: string | number): string; +/** + * Decode path section of URL (consitant with encodePath for slash encoding). + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodePath(text: string): string; +/** + * Decode query value (consitant with encodeQueryValue for plus encoding). + * + * @param text - string to decode + * @returns decoded string + */ +declare function decodeQueryValue(text: string): string; +declare function encodeHost(name?: string): string; + +interface ParsedURL { + protocol?: string; + host?: string; + auth?: string; + pathname: string; + hash: string; + search: string; +} +interface ParsedAuth { + username: string; + password: string; +} +interface ParsedHost { + hostname: string; + port: string; +} +declare function parseURL(input?: string, defaultProto?: string): ParsedURL; +declare function parsePath(input?: string): ParsedURL; +declare function parseAuth(input?: string): ParsedAuth; +declare function parseHost(input?: string): ParsedHost; +declare function stringifyParsedURL(parsed: ParsedURL): string; + +type QueryValue = string | undefined | null; +type QueryObject = Record; +declare function parseQuery(parametersString?: string): QueryObject; +declare function encodeQueryItem(key: string, value: QueryValue | QueryValue[]): string; +declare function stringifyQuery(query: QueryObject): string; + +declare class $URL implements URL { + protocol: string; + host: string; + auth: string; + pathname: string; + query: QueryObject; + hash: string; + constructor(input?: string); + get hostname(): string; + get port(): string; + get username(): string; + get password(): string; + get hasProtocol(): number; + get isAbsolute(): number | boolean; + get search(): string; + get searchParams(): URLSearchParams; + get origin(): string; + get fullpath(): string; + get encodedAuth(): string; + get href(): string; + append(url: $URL): void; + toJSON(): string; + toString(): string; +} + +declare function isRelative(inputString: string): boolean; +declare function hasProtocol(inputString: string, acceptProtocolRelative?: boolean): boolean; +declare function hasTrailingSlash(input?: string, queryParameters?: boolean): boolean; +declare function withoutTrailingSlash(input?: string, queryParameters?: boolean): string; +declare function withTrailingSlash(input?: string, queryParameters?: boolean): string; +declare function hasLeadingSlash(input?: string): boolean; +declare function withoutLeadingSlash(input?: string): string; +declare function withLeadingSlash(input?: string): string; +declare function cleanDoubleSlashes(input?: string): string; +declare function withBase(input: string, base: string): string; +declare function withoutBase(input: string, base: string): string; +declare function withQuery(input: string, query: QueryObject): string; +declare function getQuery(input: string): QueryObject; +declare function isEmptyURL(url: string): boolean; +declare function isNonEmptyURL(url: string): boolean; +declare function joinURL(base: string, ...input: string[]): string; +declare function withHttp(input: string): string; +declare function withHttps(input: string): string; +declare function withoutProtocol(input: string): string; +declare function withProtocol(input: string, protocol: string): string; +declare function createURL(input: string): $URL; +declare function normalizeURL(input: string): string; +declare function resolveURL(base: string, ...input: string[]): string; +declare function isSamePath(p1: string, p2: string): boolean; +interface CompareURLOptions { + trailingSlash?: boolean; + leadingSlash?: boolean; + encoding?: boolean; +} +declare function isEqual(a: string, b: string, options?: CompareURLOptions): boolean; + +export { $URL, ParsedAuth, ParsedHost, ParsedURL, QueryObject, QueryValue, cleanDoubleSlashes, createURL, decode, decodePath, decodeQueryValue, encode, encodeHash, encodeHost, encodeParam, encodePath, encodeQueryItem, encodeQueryKey, encodeQueryValue, getQuery, hasLeadingSlash, hasProtocol, hasTrailingSlash, isEmptyURL, isEqual, isNonEmptyURL, isRelative, isSamePath, joinURL, normalizeURL, parseAuth, parseHost, parsePath, parseQuery, parseURL, resolveURL, stringifyParsedURL, stringifyQuery, withBase, withHttp, withHttps, withLeadingSlash, withProtocol, withQuery, withTrailingSlash, withoutBase, withoutLeadingSlash, withoutProtocol, withoutTrailingSlash }; diff --git a/node_modules/ufo/dist/index.mjs b/node_modules/ufo/dist/index.mjs new file mode 100644 index 0000000..0f1ca8f --- /dev/null +++ b/node_modules/ufo/dist/index.mjs @@ -0,0 +1,454 @@ +const n = /[^\0-\x7E]/; +const t = /[\x2E\u3002\uFF0E\uFF61]/g; +const o = { overflow: "Overflow Error", "not-basic": "Illegal Input", "invalid-input": "Invalid Input" }; +const e = Math.floor; +const r = String.fromCharCode; +function s(n2) { + throw new RangeError(o[n2]); +} +const c = function(n2, t2) { + return n2 + 22 + 75 * (n2 < 26) - ((t2 != 0) << 5); +}; +const u = function(n2, t2, o2) { + let r2 = 0; + for (n2 = o2 ? e(n2 / 700) : n2 >> 1, n2 += e(n2 / t2); n2 > 455; r2 += 36) { + n2 = e(n2 / 35); + } + return e(r2 + 36 * n2 / (n2 + 38)); +}; +function toASCII(o2) { + return function(n2, o3) { + const e2 = n2.split("@"); + let r2 = ""; + e2.length > 1 && (r2 = e2[0] + "@", n2 = e2[1]); + const s2 = function(n3, t2) { + const o4 = []; + let e3 = n3.length; + for (; e3--; ) { + o4[e3] = t2(n3[e3]); + } + return o4; + }((n2 = n2.replace(t, ".")).split("."), o3).join("."); + return r2 + s2; + }(o2, function(t2) { + return n.test(t2) ? "xn--" + function(n2) { + const t3 = []; + const o3 = (n2 = function(n3) { + const t4 = []; + let o4 = 0; + const e2 = n3.length; + for (; o4 < e2; ) { + const r2 = n3.charCodeAt(o4++); + if (r2 >= 55296 && r2 <= 56319 && o4 < e2) { + const e3 = n3.charCodeAt(o4++); + (64512 & e3) == 56320 ? t4.push(((1023 & r2) << 10) + (1023 & e3) + 65536) : (t4.push(r2), o4--); + } else { + t4.push(r2); + } + } + return t4; + }(n2)).length; + let f = 128; + let i = 0; + let l = 72; + for (const o4 of n2) { + o4 < 128 && t3.push(r(o4)); + } + const h = t3.length; + let p = h; + for (h && t3.push("-"); p < o3; ) { + let o4 = 2147483647; + for (const t4 of n2) { + t4 >= f && t4 < o4 && (o4 = t4); + } + const a = p + 1; + o4 - f > e((2147483647 - i) / a) && s("overflow"), i += (o4 - f) * a, f = o4; + for (const o5 of n2) { + if (o5 < f && ++i > 2147483647 && s("overflow"), o5 == f) { + let n3 = i; + for (let o6 = 36; ; o6 += 36) { + const s2 = o6 <= l ? 1 : o6 >= l + 26 ? 26 : o6 - l; + if (n3 < s2) { + break; + } + const u2 = n3 - s2; + const f2 = 36 - s2; + t3.push(r(c(s2 + u2 % f2, 0))), n3 = e(u2 / f2); + } + t3.push(r(c(n3, 0))), l = u(i, a, p == h), i = 0, ++p; + } + } + ++i, ++f; + } + return t3.join(""); + }(t2) : t2; + }); +} + +const HASH_RE = /#/g; +const AMPERSAND_RE = /&/g; +const SLASH_RE = /\//g; +const EQUAL_RE = /=/g; +const IM_RE = /\?/g; +const PLUS_RE = /\+/g; +const ENC_BRACKET_OPEN_RE = /%5b/gi; +const ENC_BRACKET_CLOSE_RE = /%5d/gi; +const ENC_CARET_RE = /%5e/gi; +const ENC_BACKTICK_RE = /%60/gi; +const ENC_CURLY_OPEN_RE = /%7b/gi; +const ENC_PIPE_RE = /%7c/gi; +const ENC_CURLY_CLOSE_RE = /%7d/gi; +const ENC_SPACE_RE = /%20/gi; +const ENC_SLASH_RE = /%2f/gi; +const ENC_ENC_SLASH_RE = /%252f/gi; +function encode(text) { + return encodeURI("" + text).replace(ENC_PIPE_RE, "|").replace(ENC_BRACKET_OPEN_RE, "[").replace(ENC_BRACKET_CLOSE_RE, "]"); +} +function encodeHash(text) { + return encode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^"); +} +function encodeQueryValue(text) { + return encode(text).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^"); +} +function encodeQueryKey(text) { + return encodeQueryValue(text).replace(EQUAL_RE, "%3D"); +} +function encodePath(text) { + return encode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F").replace(ENC_ENC_SLASH_RE, "%2F").replace(AMPERSAND_RE, "%26").replace(PLUS_RE, "%2B"); +} +function encodeParam(text) { + return encodePath(text).replace(SLASH_RE, "%2F"); +} +function decode(text = "") { + try { + return decodeURIComponent("" + text); + } catch { + return "" + text; + } +} +function decodePath(text) { + return decode(text.replace(ENC_SLASH_RE, "%252F")); +} +function decodeQueryValue(text) { + return decode(text.replace(PLUS_RE, " ")); +} +function encodeHost(name = "") { + return toASCII(name); +} + +function parseQuery(parametersString = "") { + const object = {}; + if (parametersString[0] === "?") { + parametersString = parametersString.slice(1); + } + for (const parameter of parametersString.split("&")) { + const s = parameter.match(/([^=]+)=?(.*)/) || []; + if (s.length < 2) { + continue; + } + const key = decode(s[1]); + if (key === "__proto__" || key === "constructor") { + continue; + } + const value = decodeQueryValue(s[2] || ""); + if (typeof object[key] !== "undefined") { + if (Array.isArray(object[key])) { + object[key].push(value); + } else { + object[key] = [object[key], value]; + } + } else { + object[key] = value; + } + } + return object; +} +function encodeQueryItem(key, value) { + if (typeof value === "number" || typeof value === "boolean") { + value = String(value); + } + if (!value) { + return encodeQueryKey(key); + } + if (Array.isArray(value)) { + return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&"); + } + return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`; +} +function stringifyQuery(query) { + return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).join("&"); +} + +class $URL { + constructor(input = "") { + this.query = {}; + if (typeof input !== "string") { + throw new TypeError(`URL input should be string received ${typeof input} (${input})`); + } + const parsed = parseURL(input); + this.protocol = decode(parsed.protocol); + this.host = decode(parsed.host); + this.auth = decode(parsed.auth); + this.pathname = decodePath(parsed.pathname); + this.query = parseQuery(parsed.search); + this.hash = decode(parsed.hash); + } + get hostname() { + return parseHost(this.host).hostname; + } + get port() { + return parseHost(this.host).port || ""; + } + get username() { + return parseAuth(this.auth).username; + } + get password() { + return parseAuth(this.auth).password || ""; + } + get hasProtocol() { + return this.protocol.length; + } + get isAbsolute() { + return this.hasProtocol || this.pathname[0] === "/"; + } + get search() { + const q = stringifyQuery(this.query); + return q.length > 0 ? "?" + q : ""; + } + get searchParams() { + const p = new URLSearchParams(); + for (const name in this.query) { + const value = this.query[name]; + if (Array.isArray(value)) { + for (const v of value) { + p.append(name, v); + } + } else { + p.append(name, value || ""); + } + } + return p; + } + get origin() { + return (this.protocol ? this.protocol + "//" : "") + encodeHost(this.host); + } + get fullpath() { + return encodePath(this.pathname) + this.search + encodeHash(this.hash); + } + get encodedAuth() { + if (!this.auth) { + return ""; + } + const { username, password } = parseAuth(this.auth); + return encodeURIComponent(username) + (password ? ":" + encodeURIComponent(password) : ""); + } + get href() { + const auth = this.encodedAuth; + const originWithAuth = (this.protocol ? this.protocol + "//" : "") + (auth ? auth + "@" : "") + encodeHost(this.host); + return this.hasProtocol && this.isAbsolute ? originWithAuth + this.fullpath : this.fullpath; + } + append(url) { + if (url.hasProtocol) { + throw new Error("Cannot append a URL with protocol"); + } + Object.assign(this.query, url.query); + if (url.pathname) { + this.pathname = withTrailingSlash(this.pathname) + withoutLeadingSlash(url.pathname); + } + if (url.hash) { + this.hash = url.hash; + } + } + toJSON() { + return this.href; + } + toString() { + return this.href; + } +} + +function isRelative(inputString) { + return ["./", "../"].some((string_) => inputString.startsWith(string_)); +} +const PROTOCOL_REGEX = /^\w{2,}:(\/\/)?/; +const PROTOCOL_RELATIVE_REGEX = /^\/\/[^/]+/; +function hasProtocol(inputString, acceptProtocolRelative = false) { + return PROTOCOL_REGEX.test(inputString) || acceptProtocolRelative && PROTOCOL_RELATIVE_REGEX.test(inputString); +} +const TRAILING_SLASH_RE = /\/$|\/\?/; +function hasTrailingSlash(input = "", queryParameters = false) { + if (!queryParameters) { + return input.endsWith("/"); + } + return TRAILING_SLASH_RE.test(input); +} +function withoutTrailingSlash(input = "", queryParameters = false) { + if (!queryParameters) { + return (hasTrailingSlash(input) ? input.slice(0, -1) : input) || "/"; + } + if (!hasTrailingSlash(input, true)) { + return input || "/"; + } + const [s0, ...s] = input.split("?"); + return (s0.slice(0, -1) || "/") + (s.length > 0 ? `?${s.join("?")}` : ""); +} +function withTrailingSlash(input = "", queryParameters = false) { + if (!queryParameters) { + return input.endsWith("/") ? input : input + "/"; + } + if (hasTrailingSlash(input, true)) { + return input || "/"; + } + const [s0, ...s] = input.split("?"); + return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : ""); +} +function hasLeadingSlash(input = "") { + return input.startsWith("/"); +} +function withoutLeadingSlash(input = "") { + return (hasLeadingSlash(input) ? input.slice(1) : input) || "/"; +} +function withLeadingSlash(input = "") { + return hasLeadingSlash(input) ? input : "/" + input; +} +function cleanDoubleSlashes(input = "") { + return input.split("://").map((string_) => string_.replace(/\/{2,}/g, "/")).join("://"); +} +function withBase(input, base) { + if (isEmptyURL(base) || hasProtocol(input)) { + return input; + } + const _base = withoutTrailingSlash(base); + if (input.startsWith(_base)) { + return input; + } + return joinURL(_base, input); +} +function withoutBase(input, base) { + if (isEmptyURL(base)) { + return input; + } + const _base = withoutTrailingSlash(base); + if (!input.startsWith(_base)) { + return input; + } + const trimmed = input.slice(_base.length); + return trimmed[0] === "/" ? trimmed : "/" + trimmed; +} +function withQuery(input, query) { + const parsed = parseURL(input); + const mergedQuery = { ...parseQuery(parsed.search), ...query }; + parsed.search = stringifyQuery(mergedQuery); + return stringifyParsedURL(parsed); +} +function getQuery(input) { + return parseQuery(parseURL(input).search); +} +function isEmptyURL(url) { + return !url || url === "/"; +} +function isNonEmptyURL(url) { + return url && url !== "/"; +} +function joinURL(base, ...input) { + let url = base || ""; + for (const index of input.filter((url2) => isNonEmptyURL(url2))) { + url = url ? withTrailingSlash(url) + withoutLeadingSlash(index) : index; + } + return url; +} +function withHttp(input) { + return withProtocol(input, "http://"); +} +function withHttps(input) { + return withProtocol(input, "https://"); +} +function withoutProtocol(input) { + return withProtocol(input, ""); +} +function withProtocol(input, protocol) { + const match = input.match(PROTOCOL_REGEX); + if (!match) { + return protocol + input; + } + return protocol + input.slice(match[0].length); +} +function createURL(input) { + return new $URL(input); +} +function normalizeURL(input) { + return createURL(input).toString(); +} +function resolveURL(base, ...input) { + const url = createURL(base); + for (const index of input.filter((url2) => isNonEmptyURL(url2))) { + url.append(createURL(index)); + } + return url.toString(); +} +function isSamePath(p1, p2) { + return decode(withoutTrailingSlash(p1)) === decode(withoutTrailingSlash(p2)); +} +function isEqual(a, b, options = {}) { + if (!options.trailingSlash) { + a = withTrailingSlash(a); + b = withTrailingSlash(b); + } + if (!options.leadingSlash) { + a = withLeadingSlash(a); + b = withLeadingSlash(b); + } + if (!options.encoding) { + a = decode(a); + b = decode(b); + } + return a === b; +} + +function parseURL(input = "", defaultProto) { + if (!hasProtocol(input, true)) { + return defaultProto ? parseURL(defaultProto + input) : parsePath(input); + } + const [protocol = "", auth, hostAndPath = ""] = (input.replace(/\\/g, "/").match(/([^/:]+:)?\/\/([^/@]+@)?(.*)/) || []).splice(1); + const [host = "", path = ""] = (hostAndPath.match(/([^#/?]*)(.*)?/) || []).splice(1); + const { pathname, search, hash } = parsePath(path.replace(/\/(?=[A-Za-z]:)/, "")); + return { + protocol, + auth: auth ? auth.slice(0, Math.max(0, auth.length - 1)) : "", + host, + pathname, + search, + hash + }; +} +function parsePath(input = "") { + const [pathname = "", search = "", hash = ""] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1); + return { + pathname, + search, + hash + }; +} +function parseAuth(input = "") { + const [username, password] = input.split(":"); + return { + username: decode(username), + password: decode(password) + }; +} +function parseHost(input = "") { + const [hostname, port] = (input.match(/([^/]*)(:0-9+)?/) || []).splice(1); + return { + hostname: decode(hostname), + port + }; +} +function stringifyParsedURL(parsed) { + const fullpath = parsed.pathname + (parsed.search ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search : "") + parsed.hash; + if (!parsed.protocol) { + return fullpath; + } + return parsed.protocol + "//" + (parsed.auth ? parsed.auth + "@" : "") + parsed.host + fullpath; +} + +export { $URL, cleanDoubleSlashes, createURL, decode, decodePath, decodeQueryValue, encode, encodeHash, encodeHost, encodeParam, encodePath, encodeQueryItem, encodeQueryKey, encodeQueryValue, getQuery, hasLeadingSlash, hasProtocol, hasTrailingSlash, isEmptyURL, isEqual, isNonEmptyURL, isRelative, isSamePath, joinURL, normalizeURL, parseAuth, parseHost, parsePath, parseQuery, parseURL, resolveURL, stringifyParsedURL, stringifyQuery, withBase, withHttp, withHttps, withLeadingSlash, withProtocol, withQuery, withTrailingSlash, withoutBase, withoutLeadingSlash, withoutProtocol, withoutTrailingSlash }; diff --git a/node_modules/ufo/package.json b/node_modules/ufo/package.json new file mode 100644 index 0000000..d850120 --- /dev/null +++ b/node_modules/ufo/package.json @@ -0,0 +1,39 @@ +{ + "name": "ufo", + "version": "1.0.1", + "description": "URL utils for humans", + "repository": "unjs/ufo", + "license": "MIT", + "sideEffects": false, + "exports": { + ".": { + "require": "./dist/index.cjs", + "import": "./dist/index.mjs" + }, + "./*": "./*" + }, + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "devDependencies": { + "@types/node": "^18.11.9", + "@vitest/coverage-c8": "^0.25.3", + "eslint": "^8.28.0", + "eslint-config-unjs": "^0.0.2", + "standard-version": "^9.5.0", + "typescript": "^4.9.3", + "unbuild": "^1.0.1", + "vitest": "^0.25.3" + }, + "packageManager": "pnpm@7.17.1", + "scripts": { + "build": "unbuild", + "dev": "vitest", + "lint": "eslint --ext .ts .", + "release": "pnpm test && standard-version && git push --follow-tags && pnpm publish", + "test": "pnpm lint && vitest run" + } +} \ No newline at end of file diff --git a/node_modules/vite-node/LICENSE b/node_modules/vite-node/LICENSE new file mode 100644 index 0000000..6e9b7d1 --- /dev/null +++ b/node_modules/vite-node/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2021-Present Anthony Fu +Copyright (c) 2021-Present Matias Capeletto + +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/vite-node/README.md b/node_modules/vite-node/README.md new file mode 100644 index 0000000..2bd2fa1 --- /dev/null +++ b/node_modules/vite-node/README.md @@ -0,0 +1,160 @@ +

+ +

+ +

+vite-node +

+

+Vite as Node runtime.
The engine powers Vitest and Nuxt 3 Dev SSR. +

+

+ +

+ +## Features + +- On-demand evaluation +- Vite's pipeline, plugins, resolve, aliasing +- Out-of-box ESM & TypeScript support +- Respect `vite.config.ts` +- Hot module replacement (HMR) +- Separate server/client architecture +- Top-level `await` +- Shims for `__dirname` and `__filename` in ESM +- Access to native node modules like `fs`, `path`, etc. + +## CLI Usage + +Run JS/TS file on Node.js using Vite's resolvers and transformers. + +```bash +npx vite-node index.ts +``` + +Options: + +```bash +npx vite-node -h +``` + +### Options via CLI + +[All `ViteNodeServer` options](https://github.com/vitest-dev/vitest/blob/main/packages/vite-node/src/types.ts#L70-L89) are supported by the CLI. They may be defined through the dot syntax, as shown below: + +```bash +npx vite-node --options.deps.inline="module-name" --options.deps.external="/module-regexp/" index.ts +``` + +Note that for options supporting RegExps, strings passed to the CLI must start _and_ end with a `/`; + +## Programmatic Usage + +In Vite Node, the server and runner (client) are separated, so you can integrate them in different contexts (workers, cross-process, or remote) if needed. The demo below shows a simple example of having both (server and runner) running in the same context + +```ts +import { createServer } from 'vite' +import { ViteNodeServer } from 'vite-node/server' +import { ViteNodeRunner } from 'vite-node/client' +import { installSourcemapsSupport } from 'vite-node/source-map' + +// create vite server +const server = await createServer({ + optimizeDeps: { + // It's recommended to disable deps optimization + disabled: true, + }, +}) +// this is need to initialize the plugins +await server.pluginContainer.buildStart({}) + +// create vite-node server +const node = new ViteNodeServer(server) + +// fixes stacktraces in Errors +installSourcemapsSupport({ + getSourceMap: source => node.getSourceMap(source), +}) + +// create vite-node runner +const runner = new ViteNodeRunner({ + root: server.config.root, + base: server.config.base, + // when having the server and runner in a different context, + // you will need to handle the communication between them + // and pass to this function + fetchModule(id) { + return node.fetchModule(id) + }, + resolveId(id, importer) { + return node.resolveId(id, importer) + }, +}) + +// execute the file +await runner.executeFile('./example.ts') + +// close the vite server +await server.close() +``` + +## Debugging + +### Debug Transformation + +Sometimes you might want to inspect the transformed code to investigate issues. You can set environment variable `VITE_NODE_DEBUG_DUMP=true` to let vite-node write the transformed result of each module under `.vite-node/dump`. + +If you want to debug by modifying the dumped code, you can change the value of `VITE_NODE_DEBUG_DUMP` to `load` and search for the dumpped files and use them for executing. + +```bash +VITE_NODE_DEBUG_DUMP=load vite-node example.ts +``` + +Or programmatically: + +```js +import { ViteNodeServer } from 'vite-node/server' + +const server = new ViteNodeServer(viteServer, { + debug: { + dumpModules: true, + loadDumppedModules: true, + } +}) +``` + +### Debug Execution + +If the process get stuck, it might because there is a unresolvable circular dependencies, you can set `VITE_NODE_DEBUG_RUNNER=true` to vite-node warn about it. + +```bash +VITE_NODE_DEBUG_RUNNER=true vite-node example.ts +``` + +Or programmatically: + +```js +import { ViteNodeRunner } from 'vite-node/client' + +const runner = new ViteNodeRunner({ + debug: true +}) +``` + +## Credits + +Based on [@pi0](https://github.com/pi0)'s brilliant idea of having a Vite server as the on-demand transforming service for [Nuxt's Vite SSR](https://github.com/nuxt/vite/pull/201). + +Thanks [@brillout](https://github.com/brillout) for kindly sharing this package name. + +## Sponsors + +

+ + + +

+ +## License + +[MIT](./LICENSE) License © 2021 [Anthony Fu](https://github.com/antfu) diff --git a/node_modules/vite-node/dist/chunk-hmr.cjs b/node_modules/vite-node/dist/chunk-hmr.cjs new file mode 100644 index 0000000..bd247e7 --- /dev/null +++ b/node_modules/vite-node/dist/chunk-hmr.cjs @@ -0,0 +1,244 @@ +'use strict'; + +var node_events = require('node:events'); +var c = require('picocolors'); +var createDebug = require('debug'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var c__default = /*#__PURE__*/_interopDefaultLegacy(c); +var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug); + +function createHmrEmitter() { + const emitter = new node_events.EventEmitter(); + return emitter; +} +function viteNodeHmrPlugin() { + const emitter = createHmrEmitter(); + return { + name: "vite-node:hmr", + configureServer(server) { + const _send = server.ws.send; + server.emitter = emitter; + server.ws.send = function(payload) { + _send(payload); + emitter.emit("message", payload); + }; + } + }; +} + +const debugHmr = createDebug__default["default"]("vite-node:hmr"); +const cache = /* @__PURE__ */ new WeakMap(); +function getCache(runner) { + if (!cache.has(runner)) { + cache.set(runner, { + hotModulesMap: /* @__PURE__ */ new Map(), + dataMap: /* @__PURE__ */ new Map(), + disposeMap: /* @__PURE__ */ new Map(), + pruneMap: /* @__PURE__ */ new Map(), + customListenersMap: /* @__PURE__ */ new Map(), + ctxToListenersMap: /* @__PURE__ */ new Map(), + messageBuffer: [], + isFirstUpdate: false, + pending: false, + queued: [] + }); + } + return cache.get(runner); +} +function sendMessageBuffer(runner, emitter) { + const maps = getCache(runner); + maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg)); + maps.messageBuffer.length = 0; +} +async function reload(runner, files) { + Array.from(runner.moduleCache.keys()).forEach((fsPath) => { + if (!fsPath.includes("node_modules")) + runner.moduleCache.delete(fsPath); + }); + return Promise.all(files.map((file) => runner.executeId(file))); +} +function notifyListeners(runner, event, data) { + const maps = getCache(runner); + const cbs = maps.customListenersMap.get(event); + if (cbs) + cbs.forEach((cb) => cb(data)); +} +async function queueUpdate(runner, p) { + const maps = getCache(runner); + maps.queued.push(p); + if (!maps.pending) { + maps.pending = true; + await Promise.resolve(); + maps.pending = false; + const loading = [...maps.queued]; + maps.queued = []; + (await Promise.all(loading)).forEach((fn) => fn && fn()); + } +} +async function fetchUpdate(runner, { path, acceptedPath }) { + const maps = getCache(runner); + const mod = maps.hotModulesMap.get(path); + if (!mod) { + return; + } + const moduleMap = /* @__PURE__ */ new Map(); + const isSelfUpdate = path === acceptedPath; + const modulesToUpdate = /* @__PURE__ */ new Set(); + if (isSelfUpdate) { + modulesToUpdate.add(path); + } else { + for (const { deps } of mod.callbacks) { + deps.forEach((dep) => { + if (acceptedPath === dep) + modulesToUpdate.add(dep); + }); + } + } + const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => { + return deps.some((dep) => modulesToUpdate.has(dep)); + }); + await Promise.all( + Array.from(modulesToUpdate).map(async (dep) => { + const disposer = maps.disposeMap.get(dep); + if (disposer) + await disposer(maps.dataMap.get(dep)); + try { + const newMod = await reload(runner, [dep]); + moduleMap.set(dep, newMod); + } catch (e) { + warnFailedFetch(e, dep); + } + }) + ); + return () => { + for (const { deps, fn } of qualifiedCallbacks) + fn(deps.map((dep) => moduleMap.get(dep))); + const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`; + console.log(`${c__default["default"].cyan("[vite-node]")} hot updated: ${loggedPath}`); + }; +} +function warnFailedFetch(err, path) { + if (!err.message.match("fetch")) + console.error(err); + console.error( + `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)` + ); +} +async function handleMessage(runner, emitter, files, payload) { + const maps = getCache(runner); + switch (payload.type) { + case "connected": + sendMessageBuffer(runner, emitter); + break; + case "update": + notifyListeners(runner, "vite:beforeUpdate", payload); + if (maps.isFirstUpdate) { + reload(runner, files); + maps.isFirstUpdate = true; + } + payload.updates.forEach((update) => { + if (update.type === "js-update") { + queueUpdate(runner, fetchUpdate(runner, update)); + } else { + console.error(`${c__default["default"].cyan("[vite-node]")} no support css hmr.}`); + } + }); + break; + case "full-reload": + notifyListeners(runner, "vite:beforeFullReload", payload); + reload(runner, files); + break; + case "prune": + notifyListeners(runner, "vite:beforePrune", payload); + payload.paths.forEach((path) => { + const fn = maps.pruneMap.get(path); + if (fn) + fn(maps.dataMap.get(path)); + }); + break; + case "error": { + notifyListeners(runner, "vite:error", payload); + const err = payload.err; + console.error(`${c__default["default"].cyan("[vite-node]")} Internal Server Error +${err.message} +${err.stack}`); + break; + } + } +} +function createHotContext(runner, emitter, files, ownerPath) { + debugHmr("createHotContext", ownerPath); + const maps = getCache(runner); + if (!maps.dataMap.has(ownerPath)) + maps.dataMap.set(ownerPath, {}); + const mod = maps.hotModulesMap.get(ownerPath); + if (mod) + mod.callbacks = []; + const newListeners = /* @__PURE__ */ new Map(); + maps.ctxToListenersMap.set(ownerPath, newListeners); + function acceptDeps(deps, callback = () => { + }) { + const mod2 = maps.hotModulesMap.get(ownerPath) || { + id: ownerPath, + callbacks: [] + }; + mod2.callbacks.push({ + deps, + fn: callback + }); + maps.hotModulesMap.set(ownerPath, mod2); + } + const hot = { + get data() { + return maps.dataMap.get(ownerPath); + }, + acceptExports(_, callback) { + acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2))); + }, + accept(deps, callback) { + if (typeof deps === "function" || !deps) { + acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2)); + } else if (typeof deps === "string") { + acceptDeps([deps], ([mod2]) => callback && callback(mod2)); + } else if (Array.isArray(deps)) { + acceptDeps(deps, callback); + } else { + throw new TypeError("invalid hot.accept() usage."); + } + }, + dispose(cb) { + maps.disposeMap.set(ownerPath, cb); + }, + prune(cb) { + maps.pruneMap.set(ownerPath, cb); + }, + invalidate() { + notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 }); + return reload(runner, files); + }, + on(event, cb) { + const addToMap = (map) => { + const existing = map.get(event) || []; + existing.push(cb); + map.set(event, existing); + }; + addToMap(maps.customListenersMap); + addToMap(newListeners); + }, + send(event, data) { + maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data })); + sendMessageBuffer(runner, emitter); + } + }; + return hot; +} + +exports.createHmrEmitter = createHmrEmitter; +exports.createHotContext = createHotContext; +exports.getCache = getCache; +exports.handleMessage = handleMessage; +exports.reload = reload; +exports.sendMessageBuffer = sendMessageBuffer; +exports.viteNodeHmrPlugin = viteNodeHmrPlugin; diff --git a/node_modules/vite-node/dist/chunk-hmr.mjs b/node_modules/vite-node/dist/chunk-hmr.mjs new file mode 100644 index 0000000..6604433 --- /dev/null +++ b/node_modules/vite-node/dist/chunk-hmr.mjs @@ -0,0 +1,231 @@ +import { EventEmitter } from 'node:events'; +import c from 'picocolors'; +import createDebug from 'debug'; + +function createHmrEmitter() { + const emitter = new EventEmitter(); + return emitter; +} +function viteNodeHmrPlugin() { + const emitter = createHmrEmitter(); + return { + name: "vite-node:hmr", + configureServer(server) { + const _send = server.ws.send; + server.emitter = emitter; + server.ws.send = function(payload) { + _send(payload); + emitter.emit("message", payload); + }; + } + }; +} + +const debugHmr = createDebug("vite-node:hmr"); +const cache = /* @__PURE__ */ new WeakMap(); +function getCache(runner) { + if (!cache.has(runner)) { + cache.set(runner, { + hotModulesMap: /* @__PURE__ */ new Map(), + dataMap: /* @__PURE__ */ new Map(), + disposeMap: /* @__PURE__ */ new Map(), + pruneMap: /* @__PURE__ */ new Map(), + customListenersMap: /* @__PURE__ */ new Map(), + ctxToListenersMap: /* @__PURE__ */ new Map(), + messageBuffer: [], + isFirstUpdate: false, + pending: false, + queued: [] + }); + } + return cache.get(runner); +} +function sendMessageBuffer(runner, emitter) { + const maps = getCache(runner); + maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg)); + maps.messageBuffer.length = 0; +} +async function reload(runner, files) { + Array.from(runner.moduleCache.keys()).forEach((fsPath) => { + if (!fsPath.includes("node_modules")) + runner.moduleCache.delete(fsPath); + }); + return Promise.all(files.map((file) => runner.executeId(file))); +} +function notifyListeners(runner, event, data) { + const maps = getCache(runner); + const cbs = maps.customListenersMap.get(event); + if (cbs) + cbs.forEach((cb) => cb(data)); +} +async function queueUpdate(runner, p) { + const maps = getCache(runner); + maps.queued.push(p); + if (!maps.pending) { + maps.pending = true; + await Promise.resolve(); + maps.pending = false; + const loading = [...maps.queued]; + maps.queued = []; + (await Promise.all(loading)).forEach((fn) => fn && fn()); + } +} +async function fetchUpdate(runner, { path, acceptedPath }) { + const maps = getCache(runner); + const mod = maps.hotModulesMap.get(path); + if (!mod) { + return; + } + const moduleMap = /* @__PURE__ */ new Map(); + const isSelfUpdate = path === acceptedPath; + const modulesToUpdate = /* @__PURE__ */ new Set(); + if (isSelfUpdate) { + modulesToUpdate.add(path); + } else { + for (const { deps } of mod.callbacks) { + deps.forEach((dep) => { + if (acceptedPath === dep) + modulesToUpdate.add(dep); + }); + } + } + const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => { + return deps.some((dep) => modulesToUpdate.has(dep)); + }); + await Promise.all( + Array.from(modulesToUpdate).map(async (dep) => { + const disposer = maps.disposeMap.get(dep); + if (disposer) + await disposer(maps.dataMap.get(dep)); + try { + const newMod = await reload(runner, [dep]); + moduleMap.set(dep, newMod); + } catch (e) { + warnFailedFetch(e, dep); + } + }) + ); + return () => { + for (const { deps, fn } of qualifiedCallbacks) + fn(deps.map((dep) => moduleMap.get(dep))); + const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`; + console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`); + }; +} +function warnFailedFetch(err, path) { + if (!err.message.match("fetch")) + console.error(err); + console.error( + `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)` + ); +} +async function handleMessage(runner, emitter, files, payload) { + const maps = getCache(runner); + switch (payload.type) { + case "connected": + sendMessageBuffer(runner, emitter); + break; + case "update": + notifyListeners(runner, "vite:beforeUpdate", payload); + if (maps.isFirstUpdate) { + reload(runner, files); + maps.isFirstUpdate = true; + } + payload.updates.forEach((update) => { + if (update.type === "js-update") { + queueUpdate(runner, fetchUpdate(runner, update)); + } else { + console.error(`${c.cyan("[vite-node]")} no support css hmr.}`); + } + }); + break; + case "full-reload": + notifyListeners(runner, "vite:beforeFullReload", payload); + reload(runner, files); + break; + case "prune": + notifyListeners(runner, "vite:beforePrune", payload); + payload.paths.forEach((path) => { + const fn = maps.pruneMap.get(path); + if (fn) + fn(maps.dataMap.get(path)); + }); + break; + case "error": { + notifyListeners(runner, "vite:error", payload); + const err = payload.err; + console.error(`${c.cyan("[vite-node]")} Internal Server Error +${err.message} +${err.stack}`); + break; + } + } +} +function createHotContext(runner, emitter, files, ownerPath) { + debugHmr("createHotContext", ownerPath); + const maps = getCache(runner); + if (!maps.dataMap.has(ownerPath)) + maps.dataMap.set(ownerPath, {}); + const mod = maps.hotModulesMap.get(ownerPath); + if (mod) + mod.callbacks = []; + const newListeners = /* @__PURE__ */ new Map(); + maps.ctxToListenersMap.set(ownerPath, newListeners); + function acceptDeps(deps, callback = () => { + }) { + const mod2 = maps.hotModulesMap.get(ownerPath) || { + id: ownerPath, + callbacks: [] + }; + mod2.callbacks.push({ + deps, + fn: callback + }); + maps.hotModulesMap.set(ownerPath, mod2); + } + const hot = { + get data() { + return maps.dataMap.get(ownerPath); + }, + acceptExports(_, callback) { + acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2))); + }, + accept(deps, callback) { + if (typeof deps === "function" || !deps) { + acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2)); + } else if (typeof deps === "string") { + acceptDeps([deps], ([mod2]) => callback && callback(mod2)); + } else if (Array.isArray(deps)) { + acceptDeps(deps, callback); + } else { + throw new TypeError("invalid hot.accept() usage."); + } + }, + dispose(cb) { + maps.disposeMap.set(ownerPath, cb); + }, + prune(cb) { + maps.pruneMap.set(ownerPath, cb); + }, + invalidate() { + notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 }); + return reload(runner, files); + }, + on(event, cb) { + const addToMap = (map) => { + const existing = map.get(event) || []; + existing.push(cb); + map.set(event, existing); + }; + addToMap(maps.customListenersMap); + addToMap(newListeners); + }, + send(event, data) { + maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data })); + sendMessageBuffer(runner, emitter); + } + }; + return hot; +} + +export { createHmrEmitter as a, createHotContext as c, getCache as g, handleMessage as h, reload as r, sendMessageBuffer as s, viteNodeHmrPlugin as v }; diff --git a/node_modules/vite-node/dist/cli.cjs b/node_modules/vite-node/dist/cli.cjs new file mode 100644 index 0000000..79cc2c6 --- /dev/null +++ b/node_modules/vite-node/dist/cli.cjs @@ -0,0 +1,103 @@ +'use strict'; + +var cac = require('cac'); +var c = require('picocolors'); +var vite = require('vite'); +var server = require('./server.cjs'); +var client = require('./client.cjs'); +var utils = require('./utils.cjs'); +var sourceMap = require('./source-map.cjs'); +var hmr = require('./chunk-hmr.cjs'); +require('perf_hooks'); +require('pathe'); +require('debug'); +require('fs'); +require('mlly'); +require('node:url'); +require('source-map-support'); +require('module'); +require('path'); +require('vm'); +require('node:events'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var cac__default = /*#__PURE__*/_interopDefaultLegacy(cac); +var c__default = /*#__PURE__*/_interopDefaultLegacy(c); + +var version = "0.27.0"; + +const cli = cac__default["default"]("vite-node"); +cli.version(version).option("-r, --root ", "Use specified root directory").option("-c, --config ", "Use specified config file").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--options ", "Use specified Vite server options").help(); +cli.command("[...files]").action(run); +cli.parse(); +async function run(files, options = {}) { + var _a; + if (!files.length) { + console.error(c__default["default"].red("No files specified.")); + cli.outputHelp(); + process.exit(1); + } + process.argv = [...process.argv.slice(0, 2), ...options["--"] || []]; + const serverOptions = options.options ? parseServerOptions(options.options) : {}; + const server$1 = await vite.createServer({ + logLevel: "error", + configFile: options.config, + root: options.root, + plugins: [ + options.watch && hmr.viteNodeHmrPlugin() + ] + }); + await server$1.pluginContainer.buildStart({}); + const node = new server.ViteNodeServer(server$1, serverOptions); + sourceMap.installSourcemapsSupport({ + getSourceMap: (source) => node.getSourceMap(source) + }); + const runner = new client.ViteNodeRunner({ + root: server$1.config.root, + base: server$1.config.base, + fetchModule(id) { + return node.fetchModule(id); + }, + resolveId(id, importer) { + return node.resolveId(id, importer); + }, + createHotContext(runner2, url) { + return hmr.createHotContext(runner2, server$1.emitter, files, url); + } + }); + await runner.executeId("/@vite/env"); + for (const file of files) + await runner.executeFile(file); + if (!options.watch) + await server$1.close(); + (_a = server$1.emitter) == null ? void 0 : _a.on("message", (payload) => { + hmr.handleMessage(runner, server$1.emitter, files, payload); + }); + if (options.watch) { + process.on("uncaughtException", (err) => { + console.error(c__default["default"].red("[vite-node] Failed to execute file: \n"), err); + }); + } +} +function parseServerOptions(serverOptions) { + var _a, _b, _c, _d, _e; + const inlineOptions = ((_a = serverOptions.deps) == null ? void 0 : _a.inline) === true ? true : utils.toArray((_b = serverOptions.deps) == null ? void 0 : _b.inline); + return { + ...serverOptions, + deps: { + ...serverOptions.deps, + inline: inlineOptions !== true ? inlineOptions.map((dep) => { + return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep; + }) : true, + external: utils.toArray((_c = serverOptions.deps) == null ? void 0 : _c.external).map((dep) => { + return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep; + }) + }, + transformMode: { + ...serverOptions.transformMode, + ssr: utils.toArray((_d = serverOptions.transformMode) == null ? void 0 : _d.ssr).map((dep) => new RegExp(dep)), + web: utils.toArray((_e = serverOptions.transformMode) == null ? void 0 : _e.web).map((dep) => new RegExp(dep)) + } + }; +} diff --git a/node_modules/vite-node/dist/cli.d.ts b/node_modules/vite-node/dist/cli.d.ts new file mode 100644 index 0000000..c0d759f --- /dev/null +++ b/node_modules/vite-node/dist/cli.d.ts @@ -0,0 +1,16 @@ +import { e as ViteNodeServerOptions } from './types-63205a44.js'; + +interface CliOptions { + root?: string; + config?: string; + watch?: boolean; + options?: ViteNodeServerOptionsCLI; + '--'?: string[]; +} +type Optional = T | undefined; +type ComputeViteNodeServerOptionsCLI> = { + [K in keyof T]: T[K] extends Optional ? string | string[] : T[K] extends Optional<(string | RegExp)[]> ? string | string[] : T[K] extends Optional<(string | RegExp)[] | true> ? string | string[] | true : T[K] extends Optional> ? ComputeViteNodeServerOptionsCLI : T[K]; +}; +type ViteNodeServerOptionsCLI = ComputeViteNodeServerOptionsCLI; + +export { CliOptions, ViteNodeServerOptionsCLI }; diff --git a/node_modules/vite-node/dist/cli.mjs b/node_modules/vite-node/dist/cli.mjs new file mode 100644 index 0000000..b798134 --- /dev/null +++ b/node_modules/vite-node/dist/cli.mjs @@ -0,0 +1,96 @@ +import cac from 'cac'; +import c from 'picocolors'; +import { createServer } from 'vite'; +import { ViteNodeServer } from './server.mjs'; +import { ViteNodeRunner } from './client.mjs'; +import { toArray } from './utils.mjs'; +import { installSourcemapsSupport } from './source-map.mjs'; +import { v as viteNodeHmrPlugin, c as createHotContext, h as handleMessage } from './chunk-hmr.mjs'; +import 'node:perf_hooks'; +import 'pathe'; +import 'debug'; +import 'node:fs'; +import 'mlly'; +import 'node:url'; +import 'source-map-support'; +import 'node:module'; +import 'node:path'; +import 'node:vm'; +import 'node:events'; + +var version = "0.27.0"; + +const cli = cac("vite-node"); +cli.version(version).option("-r, --root ", "Use specified root directory").option("-c, --config ", "Use specified config file").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--options ", "Use specified Vite server options").help(); +cli.command("[...files]").action(run); +cli.parse(); +async function run(files, options = {}) { + var _a; + if (!files.length) { + console.error(c.red("No files specified.")); + cli.outputHelp(); + process.exit(1); + } + process.argv = [...process.argv.slice(0, 2), ...options["--"] || []]; + const serverOptions = options.options ? parseServerOptions(options.options) : {}; + const server = await createServer({ + logLevel: "error", + configFile: options.config, + root: options.root, + plugins: [ + options.watch && viteNodeHmrPlugin() + ] + }); + await server.pluginContainer.buildStart({}); + const node = new ViteNodeServer(server, serverOptions); + installSourcemapsSupport({ + getSourceMap: (source) => node.getSourceMap(source) + }); + const runner = new ViteNodeRunner({ + root: server.config.root, + base: server.config.base, + fetchModule(id) { + return node.fetchModule(id); + }, + resolveId(id, importer) { + return node.resolveId(id, importer); + }, + createHotContext(runner2, url) { + return createHotContext(runner2, server.emitter, files, url); + } + }); + await runner.executeId("/@vite/env"); + for (const file of files) + await runner.executeFile(file); + if (!options.watch) + await server.close(); + (_a = server.emitter) == null ? void 0 : _a.on("message", (payload) => { + handleMessage(runner, server.emitter, files, payload); + }); + if (options.watch) { + process.on("uncaughtException", (err) => { + console.error(c.red("[vite-node] Failed to execute file: \n"), err); + }); + } +} +function parseServerOptions(serverOptions) { + var _a, _b, _c, _d, _e; + const inlineOptions = ((_a = serverOptions.deps) == null ? void 0 : _a.inline) === true ? true : toArray((_b = serverOptions.deps) == null ? void 0 : _b.inline); + return { + ...serverOptions, + deps: { + ...serverOptions.deps, + inline: inlineOptions !== true ? inlineOptions.map((dep) => { + return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep; + }) : true, + external: toArray((_c = serverOptions.deps) == null ? void 0 : _c.external).map((dep) => { + return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep; + }) + }, + transformMode: { + ...serverOptions.transformMode, + ssr: toArray((_d = serverOptions.transformMode) == null ? void 0 : _d.ssr).map((dep) => new RegExp(dep)), + web: toArray((_e = serverOptions.transformMode) == null ? void 0 : _e.web).map((dep) => new RegExp(dep)) + } + }; +} diff --git a/node_modules/vite-node/dist/client.cjs b/node_modules/vite-node/dist/client.cjs new file mode 100644 index 0000000..0535cfc --- /dev/null +++ b/node_modules/vite-node/dist/client.cjs @@ -0,0 +1,424 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var module$1 = require('module'); +var path = require('path'); +var node_url = require('node:url'); +var vm = require('vm'); +var mlly = require('mlly'); +var pathe = require('pathe'); +var createDebug = require('debug'); +var utils = require('./utils.cjs'); +var sourceMap = require('./source-map.cjs'); +require('fs'); +require('source-map-support'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var vm__default = /*#__PURE__*/_interopDefaultLegacy(vm); +var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug); + +const debugExecute = createDebug__default["default"]("vite-node:client:execute"); +const debugNative = createDebug__default["default"]("vite-node:client:native"); +const clientStub = { + injectQuery: (id) => id, + createHotContext() { + return { + accept: () => { + }, + prune: () => { + }, + dispose: () => { + }, + decline: () => { + }, + invalidate: () => { + }, + on: () => { + } + }; + }, + updateStyle(id, css) { + if (typeof document === "undefined") + return; + const element = document.getElementById(id); + if (element) + element.remove(); + const head = document.querySelector("head"); + const style = document.createElement("style"); + style.setAttribute("type", "text/css"); + style.id = id; + style.innerHTML = css; + head == null ? void 0 : head.appendChild(style); + } +}; +const DEFAULT_REQUEST_STUBS = { + "/@vite/client": clientStub, + "@vite/client": clientStub +}; +class ModuleCacheMap extends Map { + normalizePath(fsPath) { + return utils.normalizeModuleId(fsPath); + } + update(fsPath, mod) { + fsPath = this.normalizePath(fsPath); + if (!super.has(fsPath)) + super.set(fsPath, mod); + else + Object.assign(super.get(fsPath), mod); + return this; + } + setByModuleId(modulePath, mod) { + return super.set(modulePath, mod); + } + set(fsPath, mod) { + return this.setByModuleId(this.normalizePath(fsPath), mod); + } + getByModuleId(modulePath) { + if (!super.has(modulePath)) + super.set(modulePath, {}); + return super.get(modulePath); + } + get(fsPath) { + return this.getByModuleId(this.normalizePath(fsPath)); + } + deleteByModuleId(modulePath) { + return super.delete(modulePath); + } + delete(fsPath) { + return this.deleteByModuleId(this.normalizePath(fsPath)); + } + invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) { + for (const _id of ids) { + const id = this.normalizePath(_id); + if (invalidated.has(id)) + continue; + invalidated.add(id); + const mod = super.get(id); + if (mod == null ? void 0 : mod.importers) + this.invalidateDepTree(mod.importers, invalidated); + super.delete(id); + } + return invalidated; + } + invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) { + for (const _id of ids) { + const id = this.normalizePath(_id); + if (invalidated.has(id)) + continue; + invalidated.add(id); + const subIds = Array.from(super.entries()).filter(([, mod]) => { + var _a; + return (_a = mod.importers) == null ? void 0 : _a.has(id); + }).map(([key]) => key); + subIds.length && this.invalidateSubDepTree(subIds, invalidated); + super.delete(id); + } + return invalidated; + } + getSourceMap(id) { + const cache = this.get(id); + if (cache.map) + return cache.map; + const map = cache.code && sourceMap.extractSourceMap(cache.code); + if (map) { + cache.map = map; + return map; + } + return null; + } +} +class ViteNodeRunner { + constructor(options) { + this.options = options; + this.root = options.root ?? process.cwd(); + this.moduleCache = options.moduleCache ?? new ModuleCacheMap(); + this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false); + } + async executeFile(file) { + const url = `/@fs/${utils.slash(pathe.resolve(file))}`; + return await this.cachedRequest(url, url, []); + } + async executeId(rawId) { + const [id, url] = await this.resolveUrl(rawId); + return await this.cachedRequest(id, url, []); + } + getSourceMap(id) { + return this.moduleCache.getSourceMap(id); + } + async cachedRequest(id, fsPath, callstack) { + const importee = callstack[callstack.length - 1]; + const mod = this.moduleCache.get(fsPath); + if (!mod.importers) + mod.importers = /* @__PURE__ */ new Set(); + if (importee) + mod.importers.add(importee); + if (callstack.includes(fsPath) && mod.exports) + return mod.exports; + if (mod.promise) + return mod.promise; + const promise = this.directRequest(id, fsPath, callstack); + Object.assign(mod, { promise, evaluated: false }); + try { + return await promise; + } finally { + mod.evaluated = true; + } + } + shouldResolveId(id, _importee) { + return !utils.isInternalRequest(id) && !mlly.isNodeBuiltin(id); + } + async _resolveUrl(id, importee) { + if (!this.shouldResolveId(id)) + return [id, id]; + if (importee && id.startsWith(utils.VALID_ID_PREFIX)) + importee = void 0; + id = utils.normalizeRequestId(id, this.options.base); + if (!this.options.resolveId) + return [id, utils.toFilePath(id, this.root)]; + const resolved = await this.options.resolveId(id, importee); + const resolvedId = resolved ? utils.normalizeRequestId(resolved.id, this.options.base) : id; + const fsPath = resolved ? resolvedId : utils.toFilePath(id, this.root); + return [resolvedId, fsPath]; + } + async resolveUrl(id, importee) { + const resolveKey = `resolve:${id}`; + this.moduleCache.setByModuleId(resolveKey, { resolving: true }); + try { + return await this._resolveUrl(id, importee); + } finally { + this.moduleCache.deleteByModuleId(resolveKey); + } + } + async dependencyRequest(id, fsPath, callstack) { + var _a; + const getStack = () => { + return `stack: +${[...callstack, fsPath].reverse().map((p) => `- ${p}`).join("\n")}`; + }; + let debugTimer; + if (this.debug) + debugTimer = setTimeout(() => console.warn(() => `module ${fsPath} takes over 2s to load. +${getStack()}`), 2e3); + try { + if (callstack.includes(fsPath)) { + const depExports = (_a = this.moduleCache.get(fsPath)) == null ? void 0 : _a.exports; + if (depExports) + return depExports; + throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`); + } + return await this.cachedRequest(id, fsPath, callstack); + } finally { + if (debugTimer) + clearTimeout(debugTimer); + } + } + async directRequest(id, fsPath, _callstack) { + const moduleId = utils.normalizeModuleId(fsPath); + const callstack = [..._callstack, moduleId]; + const mod = this.moduleCache.getByModuleId(moduleId); + const request = async (dep) => { + const [id2, depFsPath] = await this.resolveUrl(dep, fsPath); + return this.dependencyRequest(id2, depFsPath, callstack); + }; + const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS; + if (id in requestStubs) + return requestStubs[id]; + let { code: transformed, externalize } = await this.options.fetchModule(id); + if (externalize) { + debugNative(externalize); + const exports2 = await this.interopedImport(externalize); + mod.exports = exports2; + return exports2; + } + if (transformed == null) + throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`); + const modulePath = utils.cleanUrl(moduleId); + const href = node_url.pathToFileURL(modulePath).href; + const meta = { url: href }; + const exports = /* @__PURE__ */ Object.create(null); + Object.defineProperty(exports, Symbol.toStringTag, { + value: "Module", + enumerable: false, + configurable: false + }); + const cjsExports = new Proxy(exports, { + set: (_, p, value) => { + if (p === "default" && this.shouldInterop(modulePath, { default: value })) { + exportAll(cjsExports, value); + exports.default = value; + return true; + } + if (!Reflect.has(exports, "default")) + exports.default = {}; + if (utils.isPrimitive(exports.default)) { + defineExport(exports, p, () => void 0); + return true; + } + exports.default[p] = value; + if (p !== "default") + defineExport(exports, p, () => value); + return true; + } + }); + Object.assign(mod, { code: transformed, exports }); + const __filename = node_url.fileURLToPath(href); + const moduleProxy = { + set exports(value) { + exportAll(cjsExports, value); + exports.default = value; + }, + get exports() { + return cjsExports; + } + }; + let hotContext; + if (this.options.createHotContext) { + Object.defineProperty(meta, "hot", { + enumerable: true, + get: () => { + var _a, _b; + hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`)); + return hotContext; + }, + set: (value) => { + hotContext = value; + } + }); + } + const context = this.prepareContext({ + __vite_ssr_import__: request, + __vite_ssr_dynamic_import__: request, + __vite_ssr_exports__: exports, + __vite_ssr_exportAll__: (obj) => exportAll(exports, obj), + __vite_ssr_import_meta__: meta, + require: module$1.createRequire(href), + exports: cjsExports, + module: moduleProxy, + __filename, + __dirname: path.dirname(__filename) + }); + debugExecute(__filename); + if (transformed[0] === "#") + transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length)); + const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`; + const code = `${codeDefinition}${transformed} +}}`; + const fn = vm__default["default"].runInThisContext(code, { + filename: __filename, + lineOffset: 0, + columnOffset: -codeDefinition.length + }); + await fn(...Object.values(context)); + return exports; + } + prepareContext(context) { + return context; + } + shouldInterop(path, mod) { + if (this.options.interopDefault === false) + return false; + return !path.endsWith(".mjs") && "default" in mod; + } + async interopedImport(path) { + const importedModule = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(path); + if (!this.shouldInterop(path, importedModule)) + return importedModule; + const { mod, defaultExport } = interopModule(importedModule); + const modKeys = Reflect.ownKeys(mod); + let defaultKeys = !utils.isPrimitive(defaultExport) ? Reflect.ownKeys(defaultExport) : []; + if (typeof mod !== "function" && typeof defaultExport === "function") { + const reservedKeys = ["arguments", "caller", "prototype", "name", "length"]; + defaultKeys = defaultKeys.filter((n) => typeof n === "string" && !reservedKeys.includes(n)); + } + return new Proxy(mod, { + get(mod2, prop) { + if (prop === "default") + return defaultExport; + return mod2[prop] ?? (defaultExport == null ? void 0 : defaultExport[prop]); + }, + has(mod2, prop) { + if (prop === "default") + return defaultExport !== void 0; + return prop in mod2 || defaultExport && prop in defaultExport; + }, + ownKeys() { + if (!defaultExport || utils.isPrimitive(defaultExport)) + return modKeys; + const allKeys = [...modKeys, "default", ...defaultKeys]; + return Array.from(new Set(allKeys)); + }, + getOwnPropertyDescriptor(mod2, prop) { + const descriptor = Reflect.getOwnPropertyDescriptor(mod2, prop); + if (descriptor) + return descriptor; + if (prop === "default" && defaultExport !== void 0) { + return { + value: defaultExport, + enumerable: true, + configurable: true + }; + } + } + }); + } +} +function interopModule(mod) { + if (utils.isPrimitive(mod)) { + return { + mod: { default: mod }, + defaultExport: mod + }; + } + let defaultExport = "default" in mod ? mod.default : mod; + if (!utils.isPrimitive(defaultExport) && "__esModule" in defaultExport) { + mod = defaultExport; + if ("default" in defaultExport) + defaultExport = defaultExport.default; + } + return { mod, defaultExport }; +} +function defineExport(exports, key, value) { + Object.defineProperty(exports, key, { + enumerable: true, + configurable: true, + get: value + }); +} +function exportAll(exports, sourceModule) { + if (exports === sourceModule) + return; + if (utils.isPrimitive(sourceModule) || Array.isArray(sourceModule)) + return; + for (const key in sourceModule) { + if (key !== "default") { + try { + defineExport(exports, key, () => sourceModule[key]); + } catch (_err) { + } + } + } +} + +exports.DEFAULT_REQUEST_STUBS = DEFAULT_REQUEST_STUBS; +exports.ModuleCacheMap = ModuleCacheMap; +exports.ViteNodeRunner = ViteNodeRunner; diff --git a/node_modules/vite-node/dist/client.d.ts b/node_modules/vite-node/dist/client.d.ts new file mode 100644 index 0000000..bc960d3 --- /dev/null +++ b/node_modules/vite-node/dist/client.d.ts @@ -0,0 +1 @@ +export { j as DEFAULT_REQUEST_STUBS, M as ModuleCacheMap, h as ViteNodeRunner } from './types-63205a44.js'; diff --git a/node_modules/vite-node/dist/client.mjs b/node_modules/vite-node/dist/client.mjs new file mode 100644 index 0000000..bd5b599 --- /dev/null +++ b/node_modules/vite-node/dist/client.mjs @@ -0,0 +1,395 @@ +import { createRequire } from 'node:module'; +import { dirname } from 'node:path'; +import { pathToFileURL, fileURLToPath } from 'node:url'; +import vm from 'node:vm'; +import { isNodeBuiltin } from 'mlly'; +import { resolve } from 'pathe'; +import createDebug from 'debug'; +import { normalizeModuleId, slash, isInternalRequest, VALID_ID_PREFIX, normalizeRequestId, toFilePath, cleanUrl, isPrimitive } from './utils.mjs'; +import { extractSourceMap } from './source-map.mjs'; +import 'node:fs'; +import 'source-map-support'; + +const debugExecute = createDebug("vite-node:client:execute"); +const debugNative = createDebug("vite-node:client:native"); +const clientStub = { + injectQuery: (id) => id, + createHotContext() { + return { + accept: () => { + }, + prune: () => { + }, + dispose: () => { + }, + decline: () => { + }, + invalidate: () => { + }, + on: () => { + } + }; + }, + updateStyle(id, css) { + if (typeof document === "undefined") + return; + const element = document.getElementById(id); + if (element) + element.remove(); + const head = document.querySelector("head"); + const style = document.createElement("style"); + style.setAttribute("type", "text/css"); + style.id = id; + style.innerHTML = css; + head == null ? void 0 : head.appendChild(style); + } +}; +const DEFAULT_REQUEST_STUBS = { + "/@vite/client": clientStub, + "@vite/client": clientStub +}; +class ModuleCacheMap extends Map { + normalizePath(fsPath) { + return normalizeModuleId(fsPath); + } + update(fsPath, mod) { + fsPath = this.normalizePath(fsPath); + if (!super.has(fsPath)) + super.set(fsPath, mod); + else + Object.assign(super.get(fsPath), mod); + return this; + } + setByModuleId(modulePath, mod) { + return super.set(modulePath, mod); + } + set(fsPath, mod) { + return this.setByModuleId(this.normalizePath(fsPath), mod); + } + getByModuleId(modulePath) { + if (!super.has(modulePath)) + super.set(modulePath, {}); + return super.get(modulePath); + } + get(fsPath) { + return this.getByModuleId(this.normalizePath(fsPath)); + } + deleteByModuleId(modulePath) { + return super.delete(modulePath); + } + delete(fsPath) { + return this.deleteByModuleId(this.normalizePath(fsPath)); + } + invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) { + for (const _id of ids) { + const id = this.normalizePath(_id); + if (invalidated.has(id)) + continue; + invalidated.add(id); + const mod = super.get(id); + if (mod == null ? void 0 : mod.importers) + this.invalidateDepTree(mod.importers, invalidated); + super.delete(id); + } + return invalidated; + } + invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) { + for (const _id of ids) { + const id = this.normalizePath(_id); + if (invalidated.has(id)) + continue; + invalidated.add(id); + const subIds = Array.from(super.entries()).filter(([, mod]) => { + var _a; + return (_a = mod.importers) == null ? void 0 : _a.has(id); + }).map(([key]) => key); + subIds.length && this.invalidateSubDepTree(subIds, invalidated); + super.delete(id); + } + return invalidated; + } + getSourceMap(id) { + const cache = this.get(id); + if (cache.map) + return cache.map; + const map = cache.code && extractSourceMap(cache.code); + if (map) { + cache.map = map; + return map; + } + return null; + } +} +class ViteNodeRunner { + constructor(options) { + this.options = options; + this.root = options.root ?? process.cwd(); + this.moduleCache = options.moduleCache ?? new ModuleCacheMap(); + this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false); + } + async executeFile(file) { + const url = `/@fs/${slash(resolve(file))}`; + return await this.cachedRequest(url, url, []); + } + async executeId(rawId) { + const [id, url] = await this.resolveUrl(rawId); + return await this.cachedRequest(id, url, []); + } + getSourceMap(id) { + return this.moduleCache.getSourceMap(id); + } + async cachedRequest(id, fsPath, callstack) { + const importee = callstack[callstack.length - 1]; + const mod = this.moduleCache.get(fsPath); + if (!mod.importers) + mod.importers = /* @__PURE__ */ new Set(); + if (importee) + mod.importers.add(importee); + if (callstack.includes(fsPath) && mod.exports) + return mod.exports; + if (mod.promise) + return mod.promise; + const promise = this.directRequest(id, fsPath, callstack); + Object.assign(mod, { promise, evaluated: false }); + try { + return await promise; + } finally { + mod.evaluated = true; + } + } + shouldResolveId(id, _importee) { + return !isInternalRequest(id) && !isNodeBuiltin(id); + } + async _resolveUrl(id, importee) { + if (!this.shouldResolveId(id)) + return [id, id]; + if (importee && id.startsWith(VALID_ID_PREFIX)) + importee = void 0; + id = normalizeRequestId(id, this.options.base); + if (!this.options.resolveId) + return [id, toFilePath(id, this.root)]; + const resolved = await this.options.resolveId(id, importee); + const resolvedId = resolved ? normalizeRequestId(resolved.id, this.options.base) : id; + const fsPath = resolved ? resolvedId : toFilePath(id, this.root); + return [resolvedId, fsPath]; + } + async resolveUrl(id, importee) { + const resolveKey = `resolve:${id}`; + this.moduleCache.setByModuleId(resolveKey, { resolving: true }); + try { + return await this._resolveUrl(id, importee); + } finally { + this.moduleCache.deleteByModuleId(resolveKey); + } + } + async dependencyRequest(id, fsPath, callstack) { + var _a; + const getStack = () => { + return `stack: +${[...callstack, fsPath].reverse().map((p) => `- ${p}`).join("\n")}`; + }; + let debugTimer; + if (this.debug) + debugTimer = setTimeout(() => console.warn(() => `module ${fsPath} takes over 2s to load. +${getStack()}`), 2e3); + try { + if (callstack.includes(fsPath)) { + const depExports = (_a = this.moduleCache.get(fsPath)) == null ? void 0 : _a.exports; + if (depExports) + return depExports; + throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`); + } + return await this.cachedRequest(id, fsPath, callstack); + } finally { + if (debugTimer) + clearTimeout(debugTimer); + } + } + async directRequest(id, fsPath, _callstack) { + const moduleId = normalizeModuleId(fsPath); + const callstack = [..._callstack, moduleId]; + const mod = this.moduleCache.getByModuleId(moduleId); + const request = async (dep) => { + const [id2, depFsPath] = await this.resolveUrl(dep, fsPath); + return this.dependencyRequest(id2, depFsPath, callstack); + }; + const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS; + if (id in requestStubs) + return requestStubs[id]; + let { code: transformed, externalize } = await this.options.fetchModule(id); + if (externalize) { + debugNative(externalize); + const exports2 = await this.interopedImport(externalize); + mod.exports = exports2; + return exports2; + } + if (transformed == null) + throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`); + const modulePath = cleanUrl(moduleId); + const href = pathToFileURL(modulePath).href; + const meta = { url: href }; + const exports = /* @__PURE__ */ Object.create(null); + Object.defineProperty(exports, Symbol.toStringTag, { + value: "Module", + enumerable: false, + configurable: false + }); + const cjsExports = new Proxy(exports, { + set: (_, p, value) => { + if (p === "default" && this.shouldInterop(modulePath, { default: value })) { + exportAll(cjsExports, value); + exports.default = value; + return true; + } + if (!Reflect.has(exports, "default")) + exports.default = {}; + if (isPrimitive(exports.default)) { + defineExport(exports, p, () => void 0); + return true; + } + exports.default[p] = value; + if (p !== "default") + defineExport(exports, p, () => value); + return true; + } + }); + Object.assign(mod, { code: transformed, exports }); + const __filename = fileURLToPath(href); + const moduleProxy = { + set exports(value) { + exportAll(cjsExports, value); + exports.default = value; + }, + get exports() { + return cjsExports; + } + }; + let hotContext; + if (this.options.createHotContext) { + Object.defineProperty(meta, "hot", { + enumerable: true, + get: () => { + var _a, _b; + hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`)); + return hotContext; + }, + set: (value) => { + hotContext = value; + } + }); + } + const context = this.prepareContext({ + __vite_ssr_import__: request, + __vite_ssr_dynamic_import__: request, + __vite_ssr_exports__: exports, + __vite_ssr_exportAll__: (obj) => exportAll(exports, obj), + __vite_ssr_import_meta__: meta, + require: createRequire(href), + exports: cjsExports, + module: moduleProxy, + __filename, + __dirname: dirname(__filename) + }); + debugExecute(__filename); + if (transformed[0] === "#") + transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length)); + const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`; + const code = `${codeDefinition}${transformed} +}}`; + const fn = vm.runInThisContext(code, { + filename: __filename, + lineOffset: 0, + columnOffset: -codeDefinition.length + }); + await fn(...Object.values(context)); + return exports; + } + prepareContext(context) { + return context; + } + shouldInterop(path, mod) { + if (this.options.interopDefault === false) + return false; + return !path.endsWith(".mjs") && "default" in mod; + } + async interopedImport(path) { + const importedModule = await import(path); + if (!this.shouldInterop(path, importedModule)) + return importedModule; + const { mod, defaultExport } = interopModule(importedModule); + const modKeys = Reflect.ownKeys(mod); + let defaultKeys = !isPrimitive(defaultExport) ? Reflect.ownKeys(defaultExport) : []; + if (typeof mod !== "function" && typeof defaultExport === "function") { + const reservedKeys = ["arguments", "caller", "prototype", "name", "length"]; + defaultKeys = defaultKeys.filter((n) => typeof n === "string" && !reservedKeys.includes(n)); + } + return new Proxy(mod, { + get(mod2, prop) { + if (prop === "default") + return defaultExport; + return mod2[prop] ?? (defaultExport == null ? void 0 : defaultExport[prop]); + }, + has(mod2, prop) { + if (prop === "default") + return defaultExport !== void 0; + return prop in mod2 || defaultExport && prop in defaultExport; + }, + ownKeys() { + if (!defaultExport || isPrimitive(defaultExport)) + return modKeys; + const allKeys = [...modKeys, "default", ...defaultKeys]; + return Array.from(new Set(allKeys)); + }, + getOwnPropertyDescriptor(mod2, prop) { + const descriptor = Reflect.getOwnPropertyDescriptor(mod2, prop); + if (descriptor) + return descriptor; + if (prop === "default" && defaultExport !== void 0) { + return { + value: defaultExport, + enumerable: true, + configurable: true + }; + } + } + }); + } +} +function interopModule(mod) { + if (isPrimitive(mod)) { + return { + mod: { default: mod }, + defaultExport: mod + }; + } + let defaultExport = "default" in mod ? mod.default : mod; + if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) { + mod = defaultExport; + if ("default" in defaultExport) + defaultExport = defaultExport.default; + } + return { mod, defaultExport }; +} +function defineExport(exports, key, value) { + Object.defineProperty(exports, key, { + enumerable: true, + configurable: true, + get: value + }); +} +function exportAll(exports, sourceModule) { + if (exports === sourceModule) + return; + if (isPrimitive(sourceModule) || Array.isArray(sourceModule)) + return; + for (const key in sourceModule) { + if (key !== "default") { + try { + defineExport(exports, key, () => sourceModule[key]); + } catch (_err) { + } + } + } +} + +export { DEFAULT_REQUEST_STUBS, ModuleCacheMap, ViteNodeRunner }; diff --git a/node_modules/vite-node/dist/hmr.cjs b/node_modules/vite-node/dist/hmr.cjs new file mode 100644 index 0000000..c6becab --- /dev/null +++ b/node_modules/vite-node/dist/hmr.cjs @@ -0,0 +1,18 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var hmr = require('./chunk-hmr.cjs'); +require('node:events'); +require('picocolors'); +require('debug'); + + + +exports.createHmrEmitter = hmr.createHmrEmitter; +exports.createHotContext = hmr.createHotContext; +exports.getCache = hmr.getCache; +exports.handleMessage = hmr.handleMessage; +exports.reload = hmr.reload; +exports.sendMessageBuffer = hmr.sendMessageBuffer; +exports.viteNodeHmrPlugin = hmr.viteNodeHmrPlugin; diff --git a/node_modules/vite-node/dist/hmr.d.ts b/node_modules/vite-node/dist/hmr.d.ts new file mode 100644 index 0000000..415269b --- /dev/null +++ b/node_modules/vite-node/dist/hmr.d.ts @@ -0,0 +1,51 @@ +import { EventEmitter } from 'node:events'; +import { HMRPayload, Plugin } from 'vite'; +import { g as CustomEventMap, h as ViteNodeRunner, i as HMRPayload$1, H as HotContext } from './types-63205a44.js'; + +type EventType = string | symbol; +type Handler = (event: T) => void; +interface Emitter> { + on(type: Key, handler: Handler): void; + off(type: Key, handler?: Handler): void; + emit(type: Key, event: Events[Key]): void; + emit(type: undefined extends Events[Key] ? Key : never): void; +} +type HMREmitter = Emitter<{ + 'message': HMRPayload; +}> & EventEmitter; +declare module 'vite' { + interface ViteDevServer { + emitter: HMREmitter; + } +} +declare function createHmrEmitter(): HMREmitter; +declare function viteNodeHmrPlugin(): Plugin; + +type InferCustomEventPayload = T extends keyof CustomEventMap ? CustomEventMap[T] : any; +interface HotModule { + id: string; + callbacks: HotCallback[]; +} +interface HotCallback { + deps: string[]; + fn: (modules: object[]) => void; +} +interface CacheData { + hotModulesMap: Map; + dataMap: Map; + disposeMap: Map void | Promise>; + pruneMap: Map void | Promise>; + customListenersMap: Map void)[]>; + ctxToListenersMap: Map void)[]>>; + messageBuffer: string[]; + isFirstUpdate: boolean; + pending: boolean; + queued: Promise<(() => void) | undefined>[]; +} +declare function getCache(runner: ViteNodeRunner): CacheData; +declare function sendMessageBuffer(runner: ViteNodeRunner, emitter: HMREmitter): void; +declare function reload(runner: ViteNodeRunner, files: string[]): Promise; +declare function handleMessage(runner: ViteNodeRunner, emitter: HMREmitter, files: string[], payload: HMRPayload$1): Promise; +declare function createHotContext(runner: ViteNodeRunner, emitter: HMREmitter, files: string[], ownerPath: string): HotContext; + +export { Emitter, EventType, HMREmitter, Handler, HotCallback, HotModule, InferCustomEventPayload, createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin }; diff --git a/node_modules/vite-node/dist/hmr.mjs b/node_modules/vite-node/dist/hmr.mjs new file mode 100644 index 0000000..3f10f57 --- /dev/null +++ b/node_modules/vite-node/dist/hmr.mjs @@ -0,0 +1,4 @@ +export { a as createHmrEmitter, c as createHotContext, g as getCache, h as handleMessage, r as reload, s as sendMessageBuffer, v as viteNodeHmrPlugin } from './chunk-hmr.mjs'; +import 'node:events'; +import 'picocolors'; +import 'debug'; diff --git a/node_modules/vite-node/dist/index.cjs b/node_modules/vite-node/dist/index.cjs new file mode 100644 index 0000000..eb109ab --- /dev/null +++ b/node_modules/vite-node/dist/index.cjs @@ -0,0 +1,2 @@ +'use strict'; + diff --git a/node_modules/vite-node/dist/index.d.ts b/node_modules/vite-node/dist/index.d.ts new file mode 100644 index 0000000..6115391 --- /dev/null +++ b/node_modules/vite-node/dist/index.d.ts @@ -0,0 +1 @@ +export { A as Arrayable, C as CreateHotContextFunction, f as DebuggerOptions, D as DepsHandlingOptions, a as FetchFunction, F as FetchResult, H as HotContext, c as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, b as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, V as ViteNodeRunnerOptions, e as ViteNodeServerOptions } from './types-63205a44.js'; diff --git a/node_modules/vite-node/dist/index.mjs b/node_modules/vite-node/dist/index.mjs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/node_modules/vite-node/dist/index.mjs @@ -0,0 +1 @@ + diff --git a/node_modules/vite-node/dist/server.cjs b/node_modules/vite-node/dist/server.cjs new file mode 100644 index 0000000..3cba04a --- /dev/null +++ b/node_modules/vite-node/dist/server.cjs @@ -0,0 +1,342 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var perf_hooks = require('perf_hooks'); +var pathe = require('pathe'); +var createDebug = require('debug'); +var fs = require('fs'); +var mlly = require('mlly'); +var utils = require('./utils.cjs'); +var c = require('picocolors'); +var sourceMap = require('./source-map.cjs'); +require('node:url'); +require('source-map-support'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug); +var c__default = /*#__PURE__*/_interopDefaultLegacy(c); + +const KNOWN_ASSET_TYPES = [ + "png", + "jpe?g", + "jfif", + "pjpeg", + "pjp", + "gif", + "svg", + "ico", + "webp", + "avif", + "mp4", + "webm", + "ogg", + "mp3", + "wav", + "flac", + "aac", + "woff2?", + "eot", + "ttf", + "otf", + "webmanifest", + "pdf", + "txt" +]; +const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/; +const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/; +const defaultInline = [ + /virtual:/, + /\.[mc]?ts$/, + /[?&](init|raw|url|inline)\b/, + new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`) +]; +const depsExternal = [ + /\.cjs\.js$/, + /\.mjs$/ +]; +function guessCJSversion(id) { + if (id.match(ESM_EXT_RE)) { + for (const i of [ + id.replace(ESM_EXT_RE, ".mjs"), + id.replace(ESM_EXT_RE, ".umd.js"), + id.replace(ESM_EXT_RE, ".cjs.js"), + id.replace(ESM_EXT_RE, ".js") + ]) { + if (fs.existsSync(i)) + return i; + } + } + if (id.match(ESM_FOLDER_RE)) { + for (const i of [ + id.replace(ESM_FOLDER_RE, "/umd/$1"), + id.replace(ESM_FOLDER_RE, "/cjs/$1"), + id.replace(ESM_FOLDER_RE, "/lib/$1"), + id.replace(ESM_FOLDER_RE, "/$1") + ]) { + if (fs.existsSync(i)) + return i; + } + } +} +const _defaultExternalizeCache = /* @__PURE__ */ new Map(); +async function shouldExternalize(id, options, cache = _defaultExternalizeCache) { + if (!cache.has(id)) + cache.set(id, _shouldExternalize(id, options)); + return cache.get(id); +} +async function _shouldExternalize(id, options) { + if (mlly.isNodeBuiltin(id)) + return id; + if (id.startsWith("data:")) + return id; + id = patchWindowsImportPath(id); + if (matchExternalizePattern(id, options == null ? void 0 : options.inline)) + return false; + if (matchExternalizePattern(id, options == null ? void 0 : options.external)) + return id; + const isNodeModule = id.includes("/node_modules/"); + const guessCJS = isNodeModule && (options == null ? void 0 : options.fallbackCJS); + id = guessCJS ? guessCJSversion(id) || id : id; + if (matchExternalizePattern(id, defaultInline)) + return false; + if (matchExternalizePattern(id, depsExternal)) + return id; + const isDist = id.includes("/dist/"); + if ((isNodeModule || isDist) && await mlly.isValidNodeImport(id)) + return id; + return false; +} +function matchExternalizePattern(id, patterns) { + if (patterns == null) + return false; + if (patterns === true) + return true; + for (const ex of patterns) { + if (typeof ex === "string") { + if (id.includes(`/node_modules/${ex}/`)) + return true; + } else { + if (ex.test(id)) + return true; + } + } + return false; +} +function patchWindowsImportPath(path) { + if (path.match(/^\w:\\/)) + return `file:///${utils.slash(path)}`; + else if (path.match(/^\w:\//)) + return `file:///${path}`; + else + return path; +} + +function hashCode(s) { + return s.split("").reduce((a, b) => { + a = (a << 5) - a + b.charCodeAt(0); + return a & a; + }, 0); +} +class Debugger { + constructor(root, options) { + this.options = options; + this.externalizeMap = /* @__PURE__ */ new Map(); + if (options.dumpModules) + this.dumpDir = pathe.resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules); + if (this.dumpDir) { + if (options.loadDumppedModules) + console.info(c__default["default"].gray(`[vite-node] [debug] load modules from ${this.dumpDir}`)); + else + console.info(c__default["default"].gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`)); + } + this.initPromise = this.clearDump(); + } + async clearDump() { + if (!this.dumpDir) + return; + if (!this.options.loadDumppedModules && fs.existsSync(this.dumpDir)) + await fs.promises.rm(this.dumpDir, { recursive: true, force: true }); + await fs.promises.mkdir(this.dumpDir, { recursive: true }); + } + encodeId(id) { + return `${id.replace(/[^\w@_-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`; + } + async recordExternalize(id, path) { + if (!this.dumpDir) + return; + this.externalizeMap.set(id, path); + await this.writeInfo(); + } + async dumpFile(id, result) { + if (!result || !this.dumpDir) + return; + await this.initPromise; + const name = this.encodeId(id); + return await fs.promises.writeFile(pathe.join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")} +${result.code}`, "utf-8"); + } + async loadDump(id) { + if (!this.dumpDir) + return null; + await this.initPromise; + const name = this.encodeId(id); + const path = pathe.join(this.dumpDir, name); + if (!fs.existsSync(path)) + return null; + const code = await fs.promises.readFile(path, "utf-8"); + return { + code: code.replace(/^\/\/.*?\n/, ""), + map: void 0 + }; + } + async writeInfo() { + if (!this.dumpDir) + return; + const info = JSON.stringify({ + time: new Date().toLocaleString(), + externalize: Object.fromEntries(this.externalizeMap.entries()) + }, null, 2); + return fs.promises.writeFile(pathe.join(this.dumpDir, "info.json"), info, "utf-8"); + } +} + +const debugRequest = createDebug__default["default"]("vite-node:server:request"); +class ViteNodeServer { + constructor(server, options = {}) { + this.server = server; + this.options = options; + this.fetchPromiseMap = /* @__PURE__ */ new Map(); + this.transformPromiseMap = /* @__PURE__ */ new Map(); + this.fetchCache = /* @__PURE__ */ new Map(); + this.externalizeCache = /* @__PURE__ */ new Map(); + var _a, _b; + const ssrOptions = server.config.ssr; + if (ssrOptions) { + options.deps ?? (options.deps = {}); + if (ssrOptions.noExternal === true) { + (_a = options.deps).inline ?? (_a.inline = true); + } else if (options.deps.inline !== true) { + (_b = options.deps).inline ?? (_b.inline = []); + options.deps.inline.push(...utils.toArray(ssrOptions.noExternal)); + } + } + if (process.env.VITE_NODE_DEBUG_DUMP) { + options.debug = Object.assign({ + dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP, + loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load" + }, options.debug ?? {}); + } + if (options.debug) + this.debugger = new Debugger(server.config.root, options.debug); + } + shouldExternalize(id) { + return shouldExternalize(id, this.options.deps, this.externalizeCache); + } + async resolveId(id, importer) { + if (importer && !importer.startsWith(this.server.config.root)) + importer = pathe.resolve(this.server.config.root, importer); + const mode = importer && this.getTransformMode(importer) || "ssr"; + return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" }); + } + getSourceMap(source) { + var _a, _b; + const fetchResult = (_a = this.fetchCache.get(source)) == null ? void 0 : _a.result; + if (fetchResult == null ? void 0 : fetchResult.map) + return fetchResult.map; + const ssrTransformResult = (_b = this.server.moduleGraph.getModuleById(source)) == null ? void 0 : _b.ssrTransformResult; + return (ssrTransformResult == null ? void 0 : ssrTransformResult.map) || null; + } + async fetchModule(id) { + id = utils.normalizeModuleId(id); + if (!this.fetchPromiseMap.has(id)) { + this.fetchPromiseMap.set( + id, + this._fetchModule(id).then((r) => { + return this.options.sourcemap !== true ? { ...r, map: void 0 } : r; + }).finally(() => { + this.fetchPromiseMap.delete(id); + }) + ); + } + return this.fetchPromiseMap.get(id); + } + async transformRequest(id) { + if (!this.transformPromiseMap.has(id)) { + this.transformPromiseMap.set( + id, + this._transformRequest(id).finally(() => { + this.transformPromiseMap.delete(id); + }) + ); + } + return this.transformPromiseMap.get(id); + } + getTransformMode(id) { + var _a, _b, _c, _d; + const withoutQuery = id.split("?")[0]; + if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r))) + return "web"; + if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.some((r) => withoutQuery.match(r))) + return "ssr"; + if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/)) + return "ssr"; + return "web"; + } + async _fetchModule(id) { + var _a; + let result; + const filePath = utils.toFilePath(id, this.server.config.root); + const module = this.server.moduleGraph.getModuleById(id); + const timestamp = module ? module.lastHMRTimestamp : null; + const cache = this.fetchCache.get(filePath); + if (timestamp !== null && cache && cache.timestamp >= timestamp) + return cache.result; + const time = Date.now(); + const externalize = await this.shouldExternalize(filePath); + let duration; + if (externalize) { + result = { externalize }; + (_a = this.debugger) == null ? void 0 : _a.recordExternalize(id, externalize); + } else { + const start = perf_hooks.performance.now(); + const r = await this._transformRequest(id); + duration = perf_hooks.performance.now() - start; + result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map }; + } + this.fetchCache.set(filePath, { + duration, + timestamp: time, + result + }); + return result; + } + async _transformRequest(id) { + var _a, _b, _c, _d; + debugRequest(id); + let result = null; + if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) { + result = await ((_b = this.debugger) == null ? void 0 : _b.loadDump(id)) ?? null; + if (result) + return result; + } + if (this.getTransformMode(id) === "web") { + result = await this.server.transformRequest(id); + if (result) + result = await this.server.ssrTransform(result.code, result.map, id); + } else { + result = await this.server.transformRequest(id, { ssr: true }); + } + const sourcemap = this.options.sourcemap ?? "inline"; + if (sourcemap === "inline" && result && !id.includes("node_modules")) + sourceMap.withInlineSourcemap(result); + if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules) + await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result)); + return result; + } +} + +exports.ViteNodeServer = ViteNodeServer; +exports.guessCJSversion = guessCJSversion; +exports.shouldExternalize = shouldExternalize; diff --git a/node_modules/vite-node/dist/server.d.ts b/node_modules/vite-node/dist/server.d.ts new file mode 100644 index 0000000..0179532 --- /dev/null +++ b/node_modules/vite-node/dist/server.d.ts @@ -0,0 +1,44 @@ +import { TransformResult, ViteDevServer } from 'vite'; +import { f as DebuggerOptions, D as DepsHandlingOptions, e as ViteNodeServerOptions, F as FetchResult, d as ViteNodeResolveId, R as RawSourceMap } from './types-63205a44.js'; + +declare class Debugger { + options: DebuggerOptions; + dumpDir: string | undefined; + initPromise: Promise | undefined; + externalizeMap: Map; + constructor(root: string, options: DebuggerOptions); + clearDump(): Promise; + encodeId(id: string): string; + recordExternalize(id: string, path: string): Promise; + dumpFile(id: string, result: TransformResult | null): Promise; + loadDump(id: string): Promise; + writeInfo(): Promise; +} + +declare function guessCJSversion(id: string): string | undefined; +declare function shouldExternalize(id: string, options?: DepsHandlingOptions, cache?: Map>): Promise; + +declare class ViteNodeServer { + server: ViteDevServer; + options: ViteNodeServerOptions; + private fetchPromiseMap; + private transformPromiseMap; + fetchCache: Map; + externalizeCache: Map>; + debugger?: Debugger; + constructor(server: ViteDevServer, options?: ViteNodeServerOptions); + shouldExternalize(id: string): Promise; + resolveId(id: string, importer?: string): Promise; + getSourceMap(source: string): RawSourceMap | null; + fetchModule(id: string): Promise; + transformRequest(id: string): Promise; + getTransformMode(id: string): "web" | "ssr"; + private _fetchModule; + private _transformRequest; +} + +export { ViteNodeServer, guessCJSversion, shouldExternalize }; diff --git a/node_modules/vite-node/dist/server.mjs b/node_modules/vite-node/dist/server.mjs new file mode 100644 index 0000000..be7acbc --- /dev/null +++ b/node_modules/vite-node/dist/server.mjs @@ -0,0 +1,331 @@ +import { performance } from 'node:perf_hooks'; +import { resolve, join } from 'pathe'; +import createDebug from 'debug'; +import { existsSync, promises } from 'node:fs'; +import { isNodeBuiltin, isValidNodeImport } from 'mlly'; +import { slash, toArray, normalizeModuleId, toFilePath } from './utils.mjs'; +import c from 'picocolors'; +import { withInlineSourcemap } from './source-map.mjs'; +import 'node:url'; +import 'source-map-support'; + +const KNOWN_ASSET_TYPES = [ + "png", + "jpe?g", + "jfif", + "pjpeg", + "pjp", + "gif", + "svg", + "ico", + "webp", + "avif", + "mp4", + "webm", + "ogg", + "mp3", + "wav", + "flac", + "aac", + "woff2?", + "eot", + "ttf", + "otf", + "webmanifest", + "pdf", + "txt" +]; +const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/; +const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/; +const defaultInline = [ + /virtual:/, + /\.[mc]?ts$/, + /[?&](init|raw|url|inline)\b/, + new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`) +]; +const depsExternal = [ + /\.cjs\.js$/, + /\.mjs$/ +]; +function guessCJSversion(id) { + if (id.match(ESM_EXT_RE)) { + for (const i of [ + id.replace(ESM_EXT_RE, ".mjs"), + id.replace(ESM_EXT_RE, ".umd.js"), + id.replace(ESM_EXT_RE, ".cjs.js"), + id.replace(ESM_EXT_RE, ".js") + ]) { + if (existsSync(i)) + return i; + } + } + if (id.match(ESM_FOLDER_RE)) { + for (const i of [ + id.replace(ESM_FOLDER_RE, "/umd/$1"), + id.replace(ESM_FOLDER_RE, "/cjs/$1"), + id.replace(ESM_FOLDER_RE, "/lib/$1"), + id.replace(ESM_FOLDER_RE, "/$1") + ]) { + if (existsSync(i)) + return i; + } + } +} +const _defaultExternalizeCache = /* @__PURE__ */ new Map(); +async function shouldExternalize(id, options, cache = _defaultExternalizeCache) { + if (!cache.has(id)) + cache.set(id, _shouldExternalize(id, options)); + return cache.get(id); +} +async function _shouldExternalize(id, options) { + if (isNodeBuiltin(id)) + return id; + if (id.startsWith("data:")) + return id; + id = patchWindowsImportPath(id); + if (matchExternalizePattern(id, options == null ? void 0 : options.inline)) + return false; + if (matchExternalizePattern(id, options == null ? void 0 : options.external)) + return id; + const isNodeModule = id.includes("/node_modules/"); + const guessCJS = isNodeModule && (options == null ? void 0 : options.fallbackCJS); + id = guessCJS ? guessCJSversion(id) || id : id; + if (matchExternalizePattern(id, defaultInline)) + return false; + if (matchExternalizePattern(id, depsExternal)) + return id; + const isDist = id.includes("/dist/"); + if ((isNodeModule || isDist) && await isValidNodeImport(id)) + return id; + return false; +} +function matchExternalizePattern(id, patterns) { + if (patterns == null) + return false; + if (patterns === true) + return true; + for (const ex of patterns) { + if (typeof ex === "string") { + if (id.includes(`/node_modules/${ex}/`)) + return true; + } else { + if (ex.test(id)) + return true; + } + } + return false; +} +function patchWindowsImportPath(path) { + if (path.match(/^\w:\\/)) + return `file:///${slash(path)}`; + else if (path.match(/^\w:\//)) + return `file:///${path}`; + else + return path; +} + +function hashCode(s) { + return s.split("").reduce((a, b) => { + a = (a << 5) - a + b.charCodeAt(0); + return a & a; + }, 0); +} +class Debugger { + constructor(root, options) { + this.options = options; + this.externalizeMap = /* @__PURE__ */ new Map(); + if (options.dumpModules) + this.dumpDir = resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules); + if (this.dumpDir) { + if (options.loadDumppedModules) + console.info(c.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`)); + else + console.info(c.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`)); + } + this.initPromise = this.clearDump(); + } + async clearDump() { + if (!this.dumpDir) + return; + if (!this.options.loadDumppedModules && existsSync(this.dumpDir)) + await promises.rm(this.dumpDir, { recursive: true, force: true }); + await promises.mkdir(this.dumpDir, { recursive: true }); + } + encodeId(id) { + return `${id.replace(/[^\w@_-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`; + } + async recordExternalize(id, path) { + if (!this.dumpDir) + return; + this.externalizeMap.set(id, path); + await this.writeInfo(); + } + async dumpFile(id, result) { + if (!result || !this.dumpDir) + return; + await this.initPromise; + const name = this.encodeId(id); + return await promises.writeFile(join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")} +${result.code}`, "utf-8"); + } + async loadDump(id) { + if (!this.dumpDir) + return null; + await this.initPromise; + const name = this.encodeId(id); + const path = join(this.dumpDir, name); + if (!existsSync(path)) + return null; + const code = await promises.readFile(path, "utf-8"); + return { + code: code.replace(/^\/\/.*?\n/, ""), + map: void 0 + }; + } + async writeInfo() { + if (!this.dumpDir) + return; + const info = JSON.stringify({ + time: new Date().toLocaleString(), + externalize: Object.fromEntries(this.externalizeMap.entries()) + }, null, 2); + return promises.writeFile(join(this.dumpDir, "info.json"), info, "utf-8"); + } +} + +const debugRequest = createDebug("vite-node:server:request"); +class ViteNodeServer { + constructor(server, options = {}) { + this.server = server; + this.options = options; + this.fetchPromiseMap = /* @__PURE__ */ new Map(); + this.transformPromiseMap = /* @__PURE__ */ new Map(); + this.fetchCache = /* @__PURE__ */ new Map(); + this.externalizeCache = /* @__PURE__ */ new Map(); + var _a, _b; + const ssrOptions = server.config.ssr; + if (ssrOptions) { + options.deps ?? (options.deps = {}); + if (ssrOptions.noExternal === true) { + (_a = options.deps).inline ?? (_a.inline = true); + } else if (options.deps.inline !== true) { + (_b = options.deps).inline ?? (_b.inline = []); + options.deps.inline.push(...toArray(ssrOptions.noExternal)); + } + } + if (process.env.VITE_NODE_DEBUG_DUMP) { + options.debug = Object.assign({ + dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP, + loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load" + }, options.debug ?? {}); + } + if (options.debug) + this.debugger = new Debugger(server.config.root, options.debug); + } + shouldExternalize(id) { + return shouldExternalize(id, this.options.deps, this.externalizeCache); + } + async resolveId(id, importer) { + if (importer && !importer.startsWith(this.server.config.root)) + importer = resolve(this.server.config.root, importer); + const mode = importer && this.getTransformMode(importer) || "ssr"; + return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" }); + } + getSourceMap(source) { + var _a, _b; + const fetchResult = (_a = this.fetchCache.get(source)) == null ? void 0 : _a.result; + if (fetchResult == null ? void 0 : fetchResult.map) + return fetchResult.map; + const ssrTransformResult = (_b = this.server.moduleGraph.getModuleById(source)) == null ? void 0 : _b.ssrTransformResult; + return (ssrTransformResult == null ? void 0 : ssrTransformResult.map) || null; + } + async fetchModule(id) { + id = normalizeModuleId(id); + if (!this.fetchPromiseMap.has(id)) { + this.fetchPromiseMap.set( + id, + this._fetchModule(id).then((r) => { + return this.options.sourcemap !== true ? { ...r, map: void 0 } : r; + }).finally(() => { + this.fetchPromiseMap.delete(id); + }) + ); + } + return this.fetchPromiseMap.get(id); + } + async transformRequest(id) { + if (!this.transformPromiseMap.has(id)) { + this.transformPromiseMap.set( + id, + this._transformRequest(id).finally(() => { + this.transformPromiseMap.delete(id); + }) + ); + } + return this.transformPromiseMap.get(id); + } + getTransformMode(id) { + var _a, _b, _c, _d; + const withoutQuery = id.split("?")[0]; + if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r))) + return "web"; + if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.some((r) => withoutQuery.match(r))) + return "ssr"; + if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/)) + return "ssr"; + return "web"; + } + async _fetchModule(id) { + var _a; + let result; + const filePath = toFilePath(id, this.server.config.root); + const module = this.server.moduleGraph.getModuleById(id); + const timestamp = module ? module.lastHMRTimestamp : null; + const cache = this.fetchCache.get(filePath); + if (timestamp !== null && cache && cache.timestamp >= timestamp) + return cache.result; + const time = Date.now(); + const externalize = await this.shouldExternalize(filePath); + let duration; + if (externalize) { + result = { externalize }; + (_a = this.debugger) == null ? void 0 : _a.recordExternalize(id, externalize); + } else { + const start = performance.now(); + const r = await this._transformRequest(id); + duration = performance.now() - start; + result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map }; + } + this.fetchCache.set(filePath, { + duration, + timestamp: time, + result + }); + return result; + } + async _transformRequest(id) { + var _a, _b, _c, _d; + debugRequest(id); + let result = null; + if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) { + result = await ((_b = this.debugger) == null ? void 0 : _b.loadDump(id)) ?? null; + if (result) + return result; + } + if (this.getTransformMode(id) === "web") { + result = await this.server.transformRequest(id); + if (result) + result = await this.server.ssrTransform(result.code, result.map, id); + } else { + result = await this.server.transformRequest(id, { ssr: true }); + } + const sourcemap = this.options.sourcemap ?? "inline"; + if (sourcemap === "inline" && result && !id.includes("node_modules")) + withInlineSourcemap(result); + if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules) + await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result)); + return result; + } +} + +export { ViteNodeServer, guessCJSversion, shouldExternalize }; diff --git a/node_modules/vite-node/dist/source-map.cjs b/node_modules/vite-node/dist/source-map.cjs new file mode 100644 index 0000000..efe81d7 --- /dev/null +++ b/node_modules/vite-node/dist/source-map.cjs @@ -0,0 +1,54 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var sourceMapSupport = require('source-map-support'); + +let SOURCEMAPPING_URL = "sourceMa"; +SOURCEMAPPING_URL += "ppingURL"; +const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node"; +const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`; +const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`); +async function withInlineSourcemap(result) { + const map = result.map; + let code = result.code; + if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE)) + return result; + const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,(.+)`, "g"); + while (OTHER_SOURCE_MAP_REGEXP.test(code)) + code = code.replace(OTHER_SOURCE_MAP_REGEXP, ""); + const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64"); + result.code = `${code.trimEnd()} + +${VITE_NODE_SOURCEMAPPING_SOURCE} +//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap} +`; + return result; +} +function extractSourceMap(code) { + var _a; + const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1]; + if (mapString) + return JSON.parse(Buffer.from(mapString, "base64").toString("utf-8")); + return null; +} +function installSourcemapsSupport(options) { + sourceMapSupport.install({ + environment: "node", + handleUncaughtExceptions: false, + retrieveSourceMap(source) { + const map = options.getSourceMap(source); + if (map) { + return { + url: source, + map + }; + } + return null; + } + }); +} + +exports.extractSourceMap = extractSourceMap; +exports.installSourcemapsSupport = installSourcemapsSupport; +exports.withInlineSourcemap = withInlineSourcemap; diff --git a/node_modules/vite-node/dist/source-map.d.ts b/node_modules/vite-node/dist/source-map.d.ts new file mode 100644 index 0000000..ba34bd6 --- /dev/null +++ b/node_modules/vite-node/dist/source-map.d.ts @@ -0,0 +1,11 @@ +import { TransformResult } from 'vite'; +import { R as RawSourceMap } from './types-63205a44.js'; + +interface InstallSourceMapSupportOptions { + getSourceMap: (source: string) => RawSourceMap | null | undefined; +} +declare function withInlineSourcemap(result: TransformResult): Promise; +declare function extractSourceMap(code: string): RawSourceMap | null; +declare function installSourcemapsSupport(options: InstallSourceMapSupportOptions): void; + +export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap }; diff --git a/node_modules/vite-node/dist/source-map.mjs b/node_modules/vite-node/dist/source-map.mjs new file mode 100644 index 0000000..60edd6d --- /dev/null +++ b/node_modules/vite-node/dist/source-map.mjs @@ -0,0 +1,48 @@ +import { install } from 'source-map-support'; + +let SOURCEMAPPING_URL = "sourceMa"; +SOURCEMAPPING_URL += "ppingURL"; +const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node"; +const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`; +const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`); +async function withInlineSourcemap(result) { + const map = result.map; + let code = result.code; + if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE)) + return result; + const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,(.+)`, "g"); + while (OTHER_SOURCE_MAP_REGEXP.test(code)) + code = code.replace(OTHER_SOURCE_MAP_REGEXP, ""); + const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64"); + result.code = `${code.trimEnd()} + +${VITE_NODE_SOURCEMAPPING_SOURCE} +//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap} +`; + return result; +} +function extractSourceMap(code) { + var _a; + const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1]; + if (mapString) + return JSON.parse(Buffer.from(mapString, "base64").toString("utf-8")); + return null; +} +function installSourcemapsSupport(options) { + install({ + environment: "node", + handleUncaughtExceptions: false, + retrieveSourceMap(source) { + const map = options.getSourceMap(source); + if (map) { + return { + url: source, + map + }; + } + return null; + } + }); +} + +export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap }; diff --git a/node_modules/vite-node/dist/types-63205a44.d.ts b/node_modules/vite-node/dist/types-63205a44.d.ts new file mode 100644 index 0000000..7bffa26 --- /dev/null +++ b/node_modules/vite-node/dist/types-63205a44.d.ts @@ -0,0 +1,289 @@ +type HMRPayload = + | ConnectedPayload + | UpdatePayload + | FullReloadPayload + | CustomPayload + | ErrorPayload + | PrunePayload + +interface ConnectedPayload { + type: 'connected' +} + +interface UpdatePayload { + type: 'update' + updates: Update[] +} + +interface Update { + type: 'js-update' | 'css-update' + path: string + acceptedPath: string + timestamp: number + /** + * @experimental internal + */ + explicitImportRequired?: boolean | undefined +} + +interface PrunePayload { + type: 'prune' + paths: string[] +} + +interface FullReloadPayload { + type: 'full-reload' + path?: string +} + +interface CustomPayload { + type: 'custom' + event: string + data?: any +} + +interface ErrorPayload { + type: 'error' + err: { + [name: string]: any + message: string + stack: string + id?: string + frame?: string + plugin?: string + pluginCode?: string + loc?: { + file?: string + line: number + column: number + } + } +} + +interface CustomEventMap { + 'vite:beforeUpdate': UpdatePayload + 'vite:afterUpdate': UpdatePayload + 'vite:beforePrune': PrunePayload + 'vite:beforeFullReload': FullReloadPayload + 'vite:error': ErrorPayload + 'vite:invalidate': InvalidatePayload +} + +interface InvalidatePayload { + path: string + message: string | undefined +} + +type InferCustomEventPayload = + T extends keyof CustomEventMap ? CustomEventMap[T] : any + +type ModuleNamespace = Record & { + [Symbol.toStringTag]: 'Module' +} + +interface ViteHotContext { + readonly data: any + + accept(): void + accept(cb: (mod: ModuleNamespace | undefined) => void): void + accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void + accept( + deps: readonly string[], + cb: (mods: Array) => void, + ): void + + acceptExports( + exportNames: string | readonly string[], + cb?: (mod: ModuleNamespace | undefined) => void, + ): void + + dispose(cb: (data: any) => void): void + prune(cb: (data: any) => void): void + invalidate(message?: string): void + + on( + event: T, + cb: (payload: InferCustomEventPayload) => void, + ): void + send(event: T, data?: InferCustomEventPayload): void +} + +declare const DEFAULT_REQUEST_STUBS: { + '/@vite/client': { + injectQuery: (id: string) => string; + createHotContext(): { + accept: () => void; + prune: () => void; + dispose: () => void; + decline: () => void; + invalidate: () => void; + on: () => void; + }; + updateStyle(id: string, css: string): void; + }; + '@vite/client': { + injectQuery: (id: string) => string; + createHotContext(): { + accept: () => void; + prune: () => void; + dispose: () => void; + decline: () => void; + invalidate: () => void; + on: () => void; + }; + updateStyle(id: string, css: string): void; + }; +}; +declare class ModuleCacheMap extends Map { + normalizePath(fsPath: string): string; + /** + * Assign partial data to the map + */ + update(fsPath: string, mod: Partial): this; + setByModuleId(modulePath: string, mod: ModuleCache): this; + set(fsPath: string, mod: ModuleCache): this; + getByModuleId(modulePath: string): ModuleCache; + get(fsPath: string): ModuleCache; + deleteByModuleId(modulePath: string): boolean; + delete(fsPath: string): boolean; + /** + * Invalidate modules that dependent on the given modules, up to the main entry + */ + invalidateDepTree(ids: string[] | Set, invalidated?: Set): Set; + /** + * Invalidate dependency modules of the given modules, down to the bottom-level dependencies + */ + invalidateSubDepTree(ids: string[] | Set, invalidated?: Set): Set; + /** + * Return parsed source map based on inlined source map of the module + */ + getSourceMap(id: string): RawSourceMap | null; +} +declare class ViteNodeRunner { + options: ViteNodeRunnerOptions; + root: string; + debug: boolean; + /** + * Holds the cache of modules + * Keys of the map are filepaths, or plain package names + */ + moduleCache: ModuleCacheMap; + constructor(options: ViteNodeRunnerOptions); + executeFile(file: string): Promise; + executeId(rawId: string): Promise; + getSourceMap(id: string): RawSourceMap | null; + /** @internal */ + cachedRequest(id: string, fsPath: string, callstack: string[]): Promise; + shouldResolveId(id: string, _importee?: string): boolean; + private _resolveUrl; + resolveUrl(id: string, importee?: string): Promise<[url: string, fsPath: string]>; + /** @internal */ + dependencyRequest(id: string, fsPath: string, callstack: string[]): Promise; + /** @internal */ + directRequest(id: string, fsPath: string, _callstack: string[]): Promise; + prepareContext(context: Record): Record; + /** + * Define if a module should be interop-ed + * This function mostly for the ability to override by subclass + */ + shouldInterop(path: string, mod: any): boolean; + /** + * Import a module and interop it + */ + interopedImport(path: string): Promise; +} + +type Nullable = T | null | undefined; +type Arrayable = T | Array; +interface DepsHandlingOptions { + external?: (string | RegExp)[]; + inline?: (string | RegExp)[] | true; + /** + * Try to guess the CJS version of a package when it's invalid ESM + * @default false + */ + fallbackCJS?: boolean; +} +interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} +interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} +interface FetchResult { + code?: string; + externalize?: string; + map?: RawSourceMap; +} +type HotContext = Omit; +type FetchFunction = (id: string) => Promise; +type ResolveIdFunction = (id: string, importer?: string) => Promise; +type CreateHotContextFunction = (runner: ViteNodeRunner, url: string) => HotContext; +interface ModuleCache { + promise?: Promise; + exports?: any; + evaluated?: boolean; + resolving?: boolean; + code?: string; + map?: RawSourceMap; + /** + * Module ids that imports this module + */ + importers?: Set; +} +interface ViteNodeRunnerOptions { + root: string; + fetchModule: FetchFunction; + resolveId?: ResolveIdFunction; + createHotContext?: CreateHotContextFunction; + base?: string; + moduleCache?: ModuleCacheMap; + interopDefault?: boolean; + requestStubs?: Record; + debug?: boolean; +} +interface ViteNodeResolveId { + external?: boolean | 'absolute' | 'relative'; + id: string; + meta?: Record | null; + moduleSideEffects?: boolean | 'no-treeshake' | null; + syntheticNamedExports?: boolean | string | null; +} +interface ViteNodeServerOptions { + /** + * Inject inline sourcemap to modules + * @default 'inline' + */ + sourcemap?: 'inline' | boolean; + /** + * Deps handling + */ + deps?: DepsHandlingOptions; + /** + * Transform method for modules + */ + transformMode?: { + ssr?: RegExp[]; + web?: RegExp[]; + }; + debug?: DebuggerOptions; +} +interface DebuggerOptions { + /** + * Dump the transformed module to filesystem + * Passing a string will dump to the specified path + */ + dumpModules?: boolean | string; + /** + * Read dumpped module from filesystem whenever exists. + * Useful for debugging by modifying the dump result from the filesystem. + */ + loadDumppedModules?: boolean; +} + +export { Arrayable as A, CreateHotContextFunction as C, DepsHandlingOptions as D, FetchResult as F, HotContext as H, ModuleCacheMap as M, Nullable as N, RawSourceMap as R, StartOfSourceMap as S, ViteNodeRunnerOptions as V, FetchFunction as a, ResolveIdFunction as b, ModuleCache as c, ViteNodeResolveId as d, ViteNodeServerOptions as e, DebuggerOptions as f, CustomEventMap as g, ViteNodeRunner as h, HMRPayload as i, DEFAULT_REQUEST_STUBS as j }; diff --git a/node_modules/vite-node/dist/types.cjs b/node_modules/vite-node/dist/types.cjs new file mode 100644 index 0000000..eb109ab --- /dev/null +++ b/node_modules/vite-node/dist/types.cjs @@ -0,0 +1,2 @@ +'use strict'; + diff --git a/node_modules/vite-node/dist/types.d.ts b/node_modules/vite-node/dist/types.d.ts new file mode 100644 index 0000000..6115391 --- /dev/null +++ b/node_modules/vite-node/dist/types.d.ts @@ -0,0 +1 @@ +export { A as Arrayable, C as CreateHotContextFunction, f as DebuggerOptions, D as DepsHandlingOptions, a as FetchFunction, F as FetchResult, H as HotContext, c as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, b as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, V as ViteNodeRunnerOptions, e as ViteNodeServerOptions } from './types-63205a44.js'; diff --git a/node_modules/vite-node/dist/types.mjs b/node_modules/vite-node/dist/types.mjs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/node_modules/vite-node/dist/types.mjs @@ -0,0 +1 @@ + diff --git a/node_modules/vite-node/dist/utils.cjs b/node_modules/vite-node/dist/utils.cjs new file mode 100644 index 0000000..41bc6aa --- /dev/null +++ b/node_modules/vite-node/dist/utils.cjs @@ -0,0 +1,70 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var node_url = require('node:url'); +var fs = require('fs'); +var pathe = require('pathe'); + +const isWindows = process.platform === "win32"; +function slash(str) { + return str.replace(/\\/g, "/"); +} +const VALID_ID_PREFIX = "/@id/"; +function normalizeRequestId(id, base) { + if (base && id.startsWith(base)) + id = `/${id.slice(base.length)}`; + return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^file:/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, ""); +} +const queryRE = /\?.*$/s; +const hashRE = /#.*$/s; +const cleanUrl = (url) => url.replace(hashRE, "").replace(queryRE, ""); +const internalRequests = [ + "@vite/client", + "@vite/env" +]; +const internalRequestRegexp = new RegExp(`^/?(${internalRequests.join("|")})$`); +const isInternalRequest = (id) => { + return internalRequestRegexp.test(id); +}; +function normalizeModuleId(id) { + return id.replace(/\\/g, "/").replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^file:\//, "/").replace(/^node:/, "").replace(/^\/+/, "/"); +} +function isPrimitive(v) { + return v !== Object(v); +} +function toFilePath(id, root) { + let absolute = (() => { + if (id.startsWith("/@fs/")) + return id.slice(4); + if (!id.startsWith(root) && id.startsWith("/")) { + const resolved = pathe.resolve(root, id.slice(1)); + if (fs.existsSync(resolved.replace(/\?.*$/, ""))) + return resolved; + } + return id; + })(); + if (absolute.startsWith("//")) + absolute = absolute.slice(1); + return isWindows && absolute.startsWith("/") ? slash(node_url.fileURLToPath(node_url.pathToFileURL(absolute.slice(1)).href)) : absolute; +} +function toArray(array) { + if (array === null || array === void 0) + array = []; + if (Array.isArray(array)) + return array; + return [array]; +} + +exports.VALID_ID_PREFIX = VALID_ID_PREFIX; +exports.cleanUrl = cleanUrl; +exports.hashRE = hashRE; +exports.isInternalRequest = isInternalRequest; +exports.isPrimitive = isPrimitive; +exports.isWindows = isWindows; +exports.normalizeModuleId = normalizeModuleId; +exports.normalizeRequestId = normalizeRequestId; +exports.queryRE = queryRE; +exports.slash = slash; +exports.toArray = toArray; +exports.toFilePath = toFilePath; diff --git a/node_modules/vite-node/dist/utils.d.ts b/node_modules/vite-node/dist/utils.d.ts new file mode 100644 index 0000000..e6445c5 --- /dev/null +++ b/node_modules/vite-node/dist/utils.d.ts @@ -0,0 +1,21 @@ +import { N as Nullable, A as Arrayable } from './types-63205a44.js'; + +declare const isWindows: boolean; +declare function slash(str: string): string; +declare const VALID_ID_PREFIX = "/@id/"; +declare function normalizeRequestId(id: string, base?: string): string; +declare const queryRE: RegExp; +declare const hashRE: RegExp; +declare const cleanUrl: (url: string) => string; +declare const isInternalRequest: (id: string) => boolean; +declare function normalizeModuleId(id: string): string; +declare function isPrimitive(v: any): boolean; +declare function toFilePath(id: string, root: string): string; +/** + * Convert `Arrayable` to `Array` + * + * @category Array + */ +declare function toArray(array?: Nullable>): Array; + +export { VALID_ID_PREFIX, cleanUrl, hashRE, isInternalRequest, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, slash, toArray, toFilePath }; diff --git a/node_modules/vite-node/dist/utils.mjs b/node_modules/vite-node/dist/utils.mjs new file mode 100644 index 0000000..0cd71d7 --- /dev/null +++ b/node_modules/vite-node/dist/utils.mjs @@ -0,0 +1,55 @@ +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { existsSync } from 'node:fs'; +import { resolve } from 'pathe'; + +const isWindows = process.platform === "win32"; +function slash(str) { + return str.replace(/\\/g, "/"); +} +const VALID_ID_PREFIX = "/@id/"; +function normalizeRequestId(id, base) { + if (base && id.startsWith(base)) + id = `/${id.slice(base.length)}`; + return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^file:/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, ""); +} +const queryRE = /\?.*$/s; +const hashRE = /#.*$/s; +const cleanUrl = (url) => url.replace(hashRE, "").replace(queryRE, ""); +const internalRequests = [ + "@vite/client", + "@vite/env" +]; +const internalRequestRegexp = new RegExp(`^/?(${internalRequests.join("|")})$`); +const isInternalRequest = (id) => { + return internalRequestRegexp.test(id); +}; +function normalizeModuleId(id) { + return id.replace(/\\/g, "/").replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^file:\//, "/").replace(/^node:/, "").replace(/^\/+/, "/"); +} +function isPrimitive(v) { + return v !== Object(v); +} +function toFilePath(id, root) { + let absolute = (() => { + if (id.startsWith("/@fs/")) + return id.slice(4); + if (!id.startsWith(root) && id.startsWith("/")) { + const resolved = resolve(root, id.slice(1)); + if (existsSync(resolved.replace(/\?.*$/, ""))) + return resolved; + } + return id; + })(); + if (absolute.startsWith("//")) + absolute = absolute.slice(1); + return isWindows && absolute.startsWith("/") ? slash(fileURLToPath(pathToFileURL(absolute.slice(1)).href)) : absolute; +} +function toArray(array) { + if (array === null || array === void 0) + array = []; + if (Array.isArray(array)) + return array; + return [array]; +} + +export { VALID_ID_PREFIX, cleanUrl, hashRE, isInternalRequest, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, slash, toArray, toFilePath }; diff --git a/node_modules/vite-node/package.json b/node_modules/vite-node/package.json new file mode 100644 index 0000000..e8c3dc5 --- /dev/null +++ b/node_modules/vite-node/package.json @@ -0,0 +1,93 @@ +{ + "name": "vite-node", + "version": "0.27.0", + "description": "Vite as Node.js runtime", + "author": "Anthony Fu ", + "license": "MIT", + "funding": "https://github.com/sponsors/antfu", + "homepage": "https://github.com/vitest-dev/vitest/blob/main/packages/vite-node#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/vite-node" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.cjs", + "import": "./dist/index.mjs" + }, + "./client": { + "types": "./dist/client.d.ts", + "require": "./dist/client.cjs", + "import": "./dist/client.mjs" + }, + "./server": { + "types": "./dist/server.d.ts", + "require": "./dist/server.cjs", + "import": "./dist/server.mjs" + }, + "./utils": { + "types": "./dist/utils.d.ts", + "require": "./dist/utils.cjs", + "import": "./dist/utils.mjs" + }, + "./hmr": { + "types": "./dist/hmr.d.ts", + "require": "./dist/hmr.cjs", + "import": "./dist/hmr.mjs" + }, + "./source-map": { + "types": "./dist/source-map.d.ts", + "require": "./dist/source-map.cjs", + "import": "./dist/source-map.mjs" + } + }, + "main": "./dist/index.mjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "typesVersions": { + "*": { + "*": [ + "./dist/*", + "./dist/index.d.ts" + ] + } + }, + "bin": { + "vite-node": "./vite-node.mjs" + }, + "files": [ + "dist", + "*.d.ts", + "*.mjs" + ], + "engines": { + "node": ">=v14.16.0" + }, + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.3.4", + "mlly": "^1.0.0", + "pathe": "^0.2.0", + "picocolors": "^1.0.0", + "source-map": "^0.6.1", + "source-map-support": "^0.5.21", + "vite": "^3.0.0 || ^4.0.0" + }, + "devDependencies": { + "@types/debug": "^4.1.7", + "@types/source-map": "^0.5.7", + "@types/source-map-support": "^0.5.6", + "rollup": "^2.79.1" + }, + "scripts": { + "build": "rimraf dist && rollup -c", + "dev": "rollup -c --watch --watch.include 'src/**' -m inline", + "typecheck": "tsc --noEmit" + } +} \ No newline at end of file diff --git a/node_modules/vite-node/vite-node.mjs b/node_modules/vite-node/vite-node.mjs new file mode 100755 index 0000000..38bbdf5 --- /dev/null +++ b/node_modules/vite-node/vite-node.mjs @@ -0,0 +1,2 @@ +#!/usr/bin/env node +import('./dist/cli.mjs') diff --git a/node_modules/vite-plugin-imba/LICENSE b/node_modules/vite-plugin-imba/LICENSE new file mode 100644 index 0000000..1eb7711 --- /dev/null +++ b/node_modules/vite-plugin-imba/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 [these people](https://github.com/imba/imba/graphs/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/vite-plugin-imba/README.md b/node_modules/vite-plugin-imba/README.md new file mode 100644 index 0000000..7341cbb --- /dev/null +++ b/node_modules/vite-plugin-imba/README.md @@ -0,0 +1,105 @@ +# vite-plugin-imba + +The official [Imba](https://imba.io) plugin for [Vite](https://vitejs.dev). + +## Usage + +```js +// vite.config.js +import { defineConfig } from 'vite'; +import { imba } from 'vite-plugin-imba'; + +export default defineConfig({ + plugins: [ + imba({ + /* plugin options */ + }) + ] +}); +``` +## Options + +### Config file + +### Config file resolving + +Besides inline options in Vite config, `vite-plugin-imba` will also automatically resolve options from an Imba config file if it exists (`imbaconfig.json` or `imba.config.js`). The JavaScript one is recommended since we'll add a `defineConfig` helper function to provide autocomplete for the options in the future + +To set a specific config file, use the `configFile` inline option. The path can be absolute or relative to the [Vite root](https://vitejs.dev/config/#root). For example: + +```js +// vite.config.js +export default defineConfig({ + plugins: [ + imba({ + configFile: 'my-imba-config.json' + }) + ] +}); +``` + +A basic Imba config looks like this: + +```js +// imba.config.js +export default { + // imba options + theme: {} +}; +``` + +### Disable automatic handling of Imba config + +Use `configFile: false` to prevent `vite-plugin-imba` from reading the config file or restarting the Vite dev server when it changes. + +```js +// vite.config.js +export default defineConfig({ + plugins: [ + imba({ + configFile: false + // your imba config here + }) + ] +}); +``` + +> Warning: +> You are responsible to provide the complete inline config when used. + +## Imba options + +These options are specific to the Imba compiler. + +### compilerOptions + +- You can specify your own pallette of colors using + +```js +// vite.config.js +export default defineConfig({ + plugins: [imba({ + compilerOptions: { + theme: { + colors: { + "myblue": "blue", + "lilac": { + "2": "hsl(253, 100%, 95%)", + "4": "hsl(252, 100%, 86%)" + }, + } + } + } + })], +}); +``` +Imba will take care of generating color variants from 1 to 9 based on the provided values. + +## Full stack Usage +In order to use the plugin both in the client and the server (with SSR and hydration), see the example in [../e2e-tests/vite-ssr-esm](../e2e-tests/vite-ssr-esm/) + +## Credits +- imba vite plugin +## License + +[MIT](./LICENSE) diff --git a/node_modules/vite-plugin-imba/dist/index.cjs b/node_modules/vite-plugin-imba/dist/index.cjs new file mode 100644 index 0000000..117c835 --- /dev/null +++ b/node_modules/vite-plugin-imba/dist/index.cjs @@ -0,0 +1,1218 @@ +globalThis.IMBA_MANIFEST={} +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: !0 }); +}, __copyProps = (to, from, except, desc) => { + if (from && typeof from == "object" || typeof from == "function") + for (let key of __getOwnPropNames(from)) + !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target, + mod +)), __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod); + +// src/index.imba +var src_exports = {}; +__export(src_exports, { + imba: () => imba +}); +module.exports = __toCommonJS(src_exports); + +// src/utils/compile.ts +var import_compiler = require("imba/compiler"); + +// src/utils/hash.ts +var crypto = __toESM(require("crypto"), 1), hashes = /* @__PURE__ */ Object.create(null), hash_length = 12; +function safeBase64Hash(input) { + if (hashes[input]) + return hashes[input]; + let md5 = crypto.createHash("md5"); + md5.update(input); + let hash = toSafe(md5.digest("base64")).slice(0, hash_length); + return hashes[input] = hash, hash; +} +var replacements = { + "+": "-", + "/": "_", + "=": "" +}, replaceRE = new RegExp(`[${Object.keys(replacements).join("")}]`, "g"); +function toSafe(base64) { + return base64.replace(replaceRE, (x) => replacements[x]); +} + +// src/utils/log.ts +var import_colors = require("kleur/colors"), import_debug = __toESM(require("debug"), 1), levels = ["debug", "info", "warn", "error", "silent"], prefix = "vite-plugin-imba", loggers = { + debug: { + log: (0, import_debug.default)(`vite:${prefix}`), + enabled: !1, + isDebug: !0 + }, + info: { + color: import_colors.cyan, + log: console.log, + enabled: !0 + }, + warn: { + color: import_colors.yellow, + log: console.warn, + enabled: !0 + }, + error: { + color: import_colors.red, + log: console.error, + enabled: !0 + }, + silent: { + enabled: !1 + } +}, _level = "info"; +function setLevel(level) { + if (level === _level) + return; + let levelIndex = levels.indexOf(level); + if (levelIndex > -1) { + _level = level; + for (let i = 0; i < levels.length; i++) + loggers[levels[i]].enabled = i >= levelIndex; + } else + _log(loggers.error, `invalid log level: ${level} `); +} +function _log(logger, message, payload) { + !logger.enabled || (logger.isDebug ? payload !== void 0 ? logger.log(message, payload) : logger.log(message) : (logger.log(logger.color(`${new Date().toLocaleTimeString()} [${prefix}] ${message}`)), payload && logger.log(payload))); +} +function createLogger(level) { + let logger = loggers[level], logFn = _log.bind(null, logger), logged = /* @__PURE__ */ new Set(), once = function(message, payload) { + logged.has(message) || (logged.add(message), logFn.apply(null, [message, payload])); + }; + return Object.defineProperty(logFn, "enabled", { + get() { + return logger.enabled; + } + }), Object.defineProperty(logFn, "once", { + get() { + return once; + } + }), logFn; +} +var log = { + debug: createLogger("debug"), + info: createLogger("info"), + warn: createLogger("warn"), + error: createLogger("error"), + setLevel +}; +function logCompilerWarnings(imbaRequest, warnings, options) { + var _a, _b, _c; + let { emitCss, onwarn, isBuild } = options, sendViaWS = !isBuild && ((_a = options.experimental) == null ? void 0 : _a.sendWarningsToBrowser), warn = isBuild ? warnBuild : warnDev, handledByDefaultWarn = [], notIgnored = warnings == null ? void 0 : warnings.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss)), extra = buildExtraWarnings(warnings, isBuild), allWarnings = [...notIgnored, ...extra]; + if (sendViaWS) { + let _warn = warn; + warn = (w) => { + handledByDefaultWarn.push(w), _warn(w); + }; + } + if (allWarnings.forEach((warning) => { + onwarn ? onwarn(warning, warn) : warn(warning); + }), sendViaWS) { + let message = { + id: imbaRequest.id, + filename: imbaRequest.filename, + normalizedFilename: imbaRequest.normalizedFilename, + timestamp: imbaRequest.timestamp, + warnings: handledByDefaultWarn, + allWarnings, + rawWarnings: warnings + }; + log.debug(`sending imba:warnings message for ${imbaRequest.normalizedFilename}`), (_c = (_b = options.server) == null ? void 0 : _b.ws) == null || _c.send("imba:warnings", message); + } +} +function ignoreCompilerWarning(warning, isBuild, emitCss) { + return !emitCss && warning.code === "css-unused-selector" || !isBuild && isNoScopableElementWarning(warning); +} +function isNoScopableElementWarning(warning) { + return warning.code === "css-unused-selector" && warning.message.includes('"*"'); +} +function buildExtraWarnings(warnings, isBuild) { + let extraWarnings = []; + if (!isBuild) { + let noScopableElementWarnings = warnings.filter((w) => isNoScopableElementWarning(w)); + if (noScopableElementWarnings.length > 0) { + let noScopableElementWarning = noScopableElementWarnings[noScopableElementWarnings.length - 1]; + extraWarnings.push({ + ...noScopableElementWarning, + code: "vite-plugin-imba-css-no-scopable-elements", + message: "No scopable elements found in template. If you're using global styles in the style tag, you should move it into an external stylesheet file and import it in JS. See https://github.com/imbajs/vite-plugin-imba/blob/main/docs/faq.md#where-should-i-put-my-global-styles." + }); + } + } + return extraWarnings; +} +function warnDev(w) { + log.info.enabled && log.info(buildExtendedLogMessage(w)); +} +function warnBuild(w) { + log.warn.enabled && log.warn(buildExtendedLogMessage(w), w.frame); +} +function buildExtendedLogMessage(w) { + let parts = []; + return w.filename && parts.push(w.filename), w.start && parts.push(":", w.start.line, ":", w.start.column), w.message && (parts.length > 0 && parts.push(" "), parts.push(w.message)), parts.join(""); +} + +// src/utils/compile.ts +var scriptLangRE = / + +{#if show_toggle} +
`${p}: 8px;`) + .join('')}`} + on:click={() => toggle()} + bind:this={toggle_el} + /> +{/if} +{#if enabled && file_loc} +
+ {file_loc} +
+{/if} + + diff --git a/node_modules/vite-plugin-imba/src/ui/inspector/load-inspector.js b/node_modules/vite-plugin-imba/src/ui/inspector/load-inspector.js new file mode 100644 index 0000000..220fbe5 --- /dev/null +++ b/node_modules/vite-plugin-imba/src/ui/inspector/load-inspector.js @@ -0,0 +1,15 @@ +// eslint-disable-next-line node/no-missing-import +import Inspector from 'virtual:imba-inspector-path:Inspector.imba'; + +function create_inspector_host() { + const id = 'imba-inspector-host'; + if (document.getElementById(id) != null) { + throw new Error('imba-inspector-host element already exists'); + } + const el = document.createElement('div'); + el.setAttribute('id', id); + document.getElementsByTagName('body')[0].appendChild(el); + return el; +} + +new Inspector({ target: create_inspector_host() }); diff --git a/node_modules/vite-plugin-imba/src/ui/inspector/plugin.ts b/node_modules/vite-plugin-imba/src/ui/inspector/plugin.ts new file mode 100644 index 0000000..1f81233 --- /dev/null +++ b/node_modules/vite-plugin-imba/src/ui/inspector/plugin.ts @@ -0,0 +1,106 @@ +import { Plugin, normalizePath } from 'vite'; +import { log } from '../../utils/log'; +import { InspectorOptions } from '../../utils/options'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import fs from 'fs'; + +const defaultInspectorOptions: InspectorOptions = { + toggleKeyCombo: process.platform === 'win32' ? 'control-shift' : 'meta-shift', + holdMode: false, + showToggleButton: 'active', + toggleButtonPos: 'top-right', + customStyles: true +}; + +function getInspectorPath() { + const pluginPath = normalizePath(path.dirname(fileURLToPath(import.meta.url))); + return pluginPath.replace(/\/vite-plugin-imba\/dist$/, '/vite-plugin-imba/src/ui/inspector/'); +} + +export function imbaInspector(): Plugin { + const inspectorPath = getInspectorPath(); + log.debug.enabled && log.debug(`imba inspector path: ${inspectorPath}`); + let inspectorOptions: InspectorOptions; + let appendTo: string | undefined; + let disabled = false; + + return { + name: 'vite-plugin-imba:inspector', + apply: 'serve', + enforce: 'pre', + + configResolved(config) { + const vps = config.plugins.find((p) => p.name === 'vite-plugin-imba'); + if (vps?.api?.options?.experimental?.inspector) { + inspectorOptions = { + ...defaultInspectorOptions, + ...vps.api.options.experimental.inspector + }; + } + if (!vps || !inspectorOptions) { + log.debug('inspector disabled, could not find config'); + disabled = true; + } else { + if (vps.api.options.kit && !inspectorOptions.appendTo) { + const out_dir = path.basename(vps.api.options.kit.outDir || '.imba-kit'); + inspectorOptions.appendTo = `${out_dir}/generated/root.imba`; + } + appendTo = inspectorOptions.appendTo; + } + }, + + async resolveId(importee: string, importer, options) { + if (options?.ssr || disabled) { + return; + } + if (importee.startsWith('virtual:imba-inspector-options')) { + return importee; + } else if (importee.startsWith('virtual:imba-inspector-path:')) { + const resolved = importee.replace('virtual:imba-inspector-path:', inspectorPath); + log.debug.enabled && log.debug(`resolved ${importee} with ${resolved}`); + return resolved; + } + }, + + async load(id, options) { + if (options?.ssr || disabled) { + return; + } + if (id === 'virtual:imba-inspector-options') { + return `export default ${JSON.stringify(inspectorOptions ?? {})}`; + } else if (id.startsWith(inspectorPath)) { + // read file ourselves to avoid getting shut out by vites fs.allow check + return await fs.promises.readFile(id, 'utf-8'); + } + }, + + transform(code: string, id: string, options?: { ssr?: boolean }) { + if (options?.ssr || disabled || !appendTo) { + return; + } + if (id.endsWith(appendTo)) { + return { code: `${code}\nimport 'virtual:imba-inspector-path:load-inspector.js'` }; + } + }, + transformIndexHtml(html) { + if (disabled || appendTo) { + return; + } + return { + html, + tags: [ + { + tag: 'script', + injectTo: 'body', + attrs: { + type: 'module', + // /@id/ is needed, otherwise the virtual: is seen as protocol by browser and cors error happens + src: '/@id/virtual:imba-inspector-path:load-inspector.js' + } + } + ] + }; + } + }; +} diff --git a/node_modules/vite-plugin-imba/src/utils/__tests__/dependencies.spec.ts b/node_modules/vite-plugin-imba/src/utils/__tests__/dependencies.spec.ts new file mode 100644 index 0000000..2fd0f86 --- /dev/null +++ b/node_modules/vite-plugin-imba/src/utils/__tests__/dependencies.spec.ts @@ -0,0 +1,43 @@ +import { describe, it, expect } from 'vitest'; +import { findRootImbaDependencies, needsOptimization } from '../dependencies'; +import * as path from 'path'; +import { createRequire } from 'module'; +import { fileURLToPath } from 'url'; +const __dir = path.dirname(fileURLToPath(import.meta.url)); +const e2eTestRoot = path.resolve(__dir, '../../../../../packages/e2e-tests'); + +describe('dependencies', () => { + describe('findRootImbaDependencies', () => { + it('should find imba dependencies in packages/e2e-test/hmr', () => { + const deps = findRootImbaDependencies(path.resolve('packages/e2e-tests/hmr')); + expect(deps).toHaveLength(1); + expect(deps[0].name).toBe('e2e-test-dep-imba-simple'); + expect(deps[0].path).toEqual([]); + }); + it('should find nested imba dependencies in packages/e2e-test/package-json-imba-field', () => { + const deps = findRootImbaDependencies(path.join(e2eTestRoot, 'package-json-imba-field')); + expect(deps).toHaveLength(3); + const hybrid = deps.find((dep) => dep.name === 'e2e-test-dep-imba-hybrid'); + expect(hybrid).toBeTruthy(); + expect(hybrid.path).toHaveLength(0); + const nested = deps.find((dep) => dep.name === 'e2e-test-dep-imba-nested'); + expect(nested).toBeTruthy(); + expect(nested.path).toHaveLength(0); + const simple = deps.find((dep) => dep.name === 'e2e-test-dep-imba-simple'); + expect(simple).toBeTruthy(); + expect(simple.path).toHaveLength(1); + expect(simple.path[0]).toBe('e2e-test-dep-imba-nested'); + }); + }); + describe('needsOptimization', () => { + it('should optimize cjs deps only', () => { + const testDepsPath = path.join(e2eTestRoot, 'dependencies/package.json'); + const localRequire = createRequire(testDepsPath); + expect(needsOptimization('e2e-test-dep-cjs-and-esm', localRequire)).toBe(false); + expect(needsOptimization('e2e-test-dep-cjs-only', localRequire)).toBe(true); + expect(needsOptimization('e2e-test-dep-esm-only', localRequire)).toBe(false); + expect(needsOptimization('e2e-test-dep-index-only', localRequire)).toBe(true); + expect(needsOptimization('e2e-test-dep-types-only', localRequire)).toBe(false); + }); + }); +}); diff --git a/node_modules/vite-plugin-imba/src/utils/__tests__/sourcemap.spec.ts b/node_modules/vite-plugin-imba/src/utils/__tests__/sourcemap.spec.ts new file mode 100644 index 0000000..e86baa2 --- /dev/null +++ b/node_modules/vite-plugin-imba/src/utils/__tests__/sourcemap.spec.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest'; +import { buildMagicString, buildSourceMap } from '../sourcemap'; + +describe('sourcemap', () => { + describe('buildMagicString', () => { + it('should return a valid magic string', async () => { + const from = 'h1{color: blue}\nh2{color: green}\nh3{color: red}\n'; + const to = 'h1{color: blue}\ndiv{color: white}\nh3{color: red}\nh2{color: green}\n'; + const m = await buildMagicString(from, to); + expect(m).toBeDefined(); + expect(m.original).toBe(from); + expect(m.toString()).toBe(to); + }); + }); + describe('buildSourceMap', () => { + it('should return a map with mappings and filename', async () => { + const map = await buildSourceMap('foo', 'bar', 'foo.txt'); + expect(map).toBeDefined(); + expect(map.mappings).toBeDefined(); + expect(map.mappings[0]).toBeDefined(); + expect(map.mappings[0][0]).toBeDefined(); + expect(map.sources[0]).toBe('foo.txt'); + }); + }); +}); diff --git a/node_modules/vite-plugin-imba/src/utils/compile.ts b/node_modules/vite-plugin-imba/src/utils/compile.ts new file mode 100644 index 0000000..c3ced5a --- /dev/null +++ b/node_modules/vite-plugin-imba/src/utils/compile.ts @@ -0,0 +1,164 @@ +import { CompileOptions, ResolvedOptions } from './options'; +import {compile} from 'imba/compiler' + +// @ts-ignore +import { createMakeHot } from 'imba-hmr'; +import { ImbaRequest } from './id'; +import { safeBase64Hash } from './hash'; +import { log } from './log'; + +const scriptLangRE = / + const filePath = id.replace(normalizePath$3(config.root), ''); + addToHTMLProxyCache(config, filePath, inlineModuleIndex, { + code: contents + }); + js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`; + shouldRemove = true; + } + everyScriptIsAsync && (everyScriptIsAsync = isAsync); + someScriptsAreAsync || (someScriptsAreAsync = isAsync); + someScriptsAreDefer || (someScriptsAreDefer = !isAsync); + } + else if (url && !isPublicFile) { + if (!isExcludedUrl(url)) { + config.logger.warn(` asset + for (const { start, end, url } of scriptUrls) { + if (!isExcludedUrl(url)) { + s.update(start, end, await urlToBuiltUrl(url, id, config, this)); + } + else if (checkPublicFile(url, config)) { + s.update(start, end, toOutputPublicFilePath(url)); + } + } + // ignore if its url can't be resolved + const resolvedStyleUrls = await Promise.all(styleUrls.map(async (styleUrl) => ({ + ...styleUrl, + resolved: await this.resolve(styleUrl.url, id) + }))); + for (const { start, end, url, resolved } of resolvedStyleUrls) { + if (resolved == null) { + config.logger.warnOnce(`\n${url} doesn't exist at build time, it will remain unchanged to be resolved at runtime`); + const importExpression = `\nimport ${JSON.stringify(url)}`; + js = js.replace(importExpression, ''); + } + else { + s.remove(start, end); + } + } + processedHtml.set(id, s.toString()); + // inject module preload polyfill only when configured and needed + const { modulePreload } = config.build; + if ((modulePreload === true || + (typeof modulePreload === 'object' && modulePreload.polyfill)) && + (someScriptsAreAsync || someScriptsAreDefer)) { + js = `import "${modulePreloadPolyfillId}";\n${js}`; + } + return js; + } + }, + async generateBundle(options, bundle) { + const analyzedChunk = new Map(); + const getImportedChunks = (chunk, seen = new Set()) => { + const chunks = []; + chunk.imports.forEach((file) => { + const importee = bundle[file]; + if (importee?.type === 'chunk' && !seen.has(file)) { + seen.add(file); + // post-order traversal + chunks.push(...getImportedChunks(importee, seen)); + chunks.push(importee); + } + }); + return chunks; + }; + const toScriptTag = (chunk, toOutputPath, isAsync) => ({ + tag: 'script', + attrs: { + ...(isAsync ? { async: true } : {}), + type: 'module', + crossorigin: true, + src: toOutputPath(chunk.fileName) + } + }); + const toPreloadTag = (filename, toOutputPath) => ({ + tag: 'link', + attrs: { + rel: 'modulepreload', + crossorigin: true, + href: toOutputPath(filename) + } + }); + const getCssTagsForChunk = (chunk, toOutputPath, seen = new Set()) => { + const tags = []; + if (!analyzedChunk.has(chunk)) { + analyzedChunk.set(chunk, 1); + chunk.imports.forEach((file) => { + const importee = bundle[file]; + if (importee?.type === 'chunk') { + tags.push(...getCssTagsForChunk(importee, toOutputPath, seen)); + } + }); + } + chunk.viteMetadata.importedCss.forEach((file) => { + if (!seen.has(file)) { + seen.add(file); + tags.push({ + tag: 'link', + attrs: { + rel: 'stylesheet', + href: toOutputPath(file) + } + }); + } + }); + return tags; + }; + for (const [id, html] of processedHtml) { + const relativeUrlPath = path$o.posix.relative(config.root, normalizePath$3(id)); + const assetsBase = getBaseInHTML(relativeUrlPath, config); + const toOutputFilePath = (filename, type) => { + if (isExternalUrl(filename)) { + return filename; + } + else { + return toOutputFilePathInHtml(filename, type, relativeUrlPath, 'html', config, (filename, importer) => assetsBase + filename); + } + }; + const toOutputAssetFilePath = (filename) => toOutputFilePath(filename, 'asset'); + const toOutputPublicAssetFilePath = (filename) => toOutputFilePath(filename, 'public'); + const isAsync = isAsyncScriptMap.get(config).get(id); + let result = html; + // find corresponding entry chunk + const chunk = Object.values(bundle).find((chunk) => chunk.type === 'chunk' && + chunk.isEntry && + chunk.facadeModuleId === id); + let canInlineEntry = false; + // inject chunk asset links + if (chunk) { + // an entry chunk can be inlined if + // - it's an ES module (e.g. not generated by the legacy plugin) + // - it contains no meaningful code other than import statements + if (options.format === 'es' && isEntirelyImport(chunk.code)) { + canInlineEntry = true; + } + // when not inlined, inject `); + }; + await traverseHtml(html, htmlPath, (node) => { + if (!nodeIsElement(node)) { + return; + } + // script tags + if (node.nodeName === 'script') { + const { src, sourceCodeLocation, isModule } = getScriptInfo(node); + if (src) { + processNodeUrl(src, sourceCodeLocation, s, config, htmlPath, originalUrl, moduleGraph); + } + else if (isModule && node.childNodes.length) { + addInlineModule(node, 'js'); + } + } + if (node.nodeName === 'style' && node.childNodes.length) { + const children = node.childNodes[0]; + styleUrl.push({ + start: children.sourceCodeLocation.startOffset, + end: children.sourceCodeLocation.endOffset, + code: children.value + }); + } + // elements with [href/src] attrs + const assetAttrs = assetAttrsConfig[node.nodeName]; + if (assetAttrs) { + for (const p of node.attrs) { + const attrKey = getAttrKey(p); + if (p.value && assetAttrs.includes(attrKey)) { + processNodeUrl(p, node.sourceCodeLocation.attrs[attrKey], s, config, htmlPath, originalUrl); + } + } + } + }); + await Promise.all(styleUrl.map(async ({ start, end, code }, index) => { + const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`; + // ensure module in graph after successful load + const mod = await moduleGraph.ensureEntryFromUrl(url, false); + ensureWatchedFile(watcher, mod.file, config.root); + const result = await server.pluginContainer.transform(code, mod.id); + s.overwrite(start, end, result?.code || ''); + })); + html = s.toString(); + return { + html, + tags: [ + { + tag: 'script', + attrs: { + type: 'module', + src: path$o.posix.join(base, CLIENT_PUBLIC_PATH) + }, + injectTo: 'head-prepend' + } + ] + }; +}; +function indexHtmlMiddleware(server) { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return async function viteIndexHtmlMiddleware(req, res, next) { + if (res.writableEnded) { + return next(); + } + const url = req.url && cleanUrl(req.url); + // htmlFallbackMiddleware appends '.html' to URLs + if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') { + const filename = getHtmlFilename(url, server); + if (fs$l.existsSync(filename)) { + try { + let html = fs$l.readFileSync(filename, 'utf-8'); + html = await server.transformIndexHtml(url, html, req.originalUrl); + return send$1(req, res, html, 'html', { + headers: server.config.server.headers + }); + } + catch (e) { + return next(e); + } + } + } + next(); + }; +} + +const logTime = createDebugger('vite:time'); +function timeMiddleware(root) { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteTimeMiddleware(req, res, next) { + const start = performance.now(); + const end = res.end; + res.end = (...args) => { + logTime(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`); + // @ts-ignore + return end.call(res, ...args); + }; + next(); + }; +} + +class ModuleNode { + /** + * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870 + */ + constructor(url, setIsSelfAccepting = true) { + /** + * Resolved file system path + query + */ + this.id = null; + this.file = null; + this.importers = new Set(); + this.importedModules = new Set(); + this.acceptedHmrDeps = new Set(); + this.acceptedHmrExports = null; + this.importedBindings = null; + this.transformResult = null; + this.ssrTransformResult = null; + this.ssrModule = null; + this.ssrError = null; + this.lastHMRTimestamp = 0; + this.lastInvalidationTimestamp = 0; + this.url = url; + this.type = isDirectCSSRequest(url) ? 'css' : 'js'; + if (setIsSelfAccepting) { + this.isSelfAccepting = false; + } + } +} +function invalidateSSRModule(mod, seen) { + if (seen.has(mod)) { + return; + } + seen.add(mod); + mod.ssrModule = null; + mod.ssrError = null; + mod.importers.forEach((importer) => invalidateSSRModule(importer, seen)); +} +class ModuleGraph { + constructor(resolveId) { + this.resolveId = resolveId; + this.urlToModuleMap = new Map(); + this.idToModuleMap = new Map(); + // a single file may corresponds to multiple modules with different queries + this.fileToModulesMap = new Map(); + this.safeModulesPath = new Set(); + } + async getModuleByUrl(rawUrl, ssr) { + const [url] = await this.resolveUrl(rawUrl, ssr); + return this.urlToModuleMap.get(url); + } + getModuleById(id) { + return this.idToModuleMap.get(removeTimestampQuery(id)); + } + getModulesByFile(file) { + return this.fileToModulesMap.get(file); + } + onFileChange(file) { + const mods = this.getModulesByFile(file); + if (mods) { + const seen = new Set(); + mods.forEach((mod) => { + this.invalidateModule(mod, seen); + }); + } + } + invalidateModule(mod, seen = new Set(), timestamp = Date.now()) { + // Save the timestamp for this invalidation, so we can avoid caching the result of possible already started + // processing being done for this module + mod.lastInvalidationTimestamp = timestamp; + // Don't invalidate mod.info and mod.meta, as they are part of the processing pipeline + // Invalidating the transform result is enough to ensure this module is re-processed next time it is requested + mod.transformResult = null; + mod.ssrTransformResult = null; + invalidateSSRModule(mod, seen); + } + invalidateAll() { + const timestamp = Date.now(); + const seen = new Set(); + this.idToModuleMap.forEach((mod) => { + this.invalidateModule(mod, seen, timestamp); + }); + } + /** + * Update the module graph based on a module's updated imports information + * If there are dependencies that no longer have any importers, they are + * returned as a Set. + */ + async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, ssr) { + mod.isSelfAccepting = isSelfAccepting; + const prevImports = mod.importedModules; + const nextImports = (mod.importedModules = new Set()); + let noLongerImported; + // update import graph + for (const imported of importedModules) { + const dep = typeof imported === 'string' + ? await this.ensureEntryFromUrl(imported, ssr) + : imported; + dep.importers.add(mod); + nextImports.add(dep); + } + // remove the importer from deps that were imported but no longer are. + prevImports.forEach((dep) => { + if (!nextImports.has(dep)) { + dep.importers.delete(mod); + if (!dep.importers.size) { + (noLongerImported || (noLongerImported = new Set())).add(dep); + } + } + }); + // update accepted hmr deps + const deps = (mod.acceptedHmrDeps = new Set()); + for (const accepted of acceptedModules) { + const dep = typeof accepted === 'string' + ? await this.ensureEntryFromUrl(accepted, ssr) + : accepted; + deps.add(dep); + } + // update accepted hmr exports + mod.acceptedHmrExports = acceptedExports; + mod.importedBindings = importedBindings; + return noLongerImported; + } + async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) { + const [url, resolvedId, meta] = await this.resolveUrl(rawUrl, ssr); + let mod = this.idToModuleMap.get(resolvedId); + if (!mod) { + mod = new ModuleNode(url, setIsSelfAccepting); + if (meta) + mod.meta = meta; + this.urlToModuleMap.set(url, mod); + mod.id = resolvedId; + this.idToModuleMap.set(resolvedId, mod); + const file = (mod.file = cleanUrl(resolvedId)); + let fileMappedModules = this.fileToModulesMap.get(file); + if (!fileMappedModules) { + fileMappedModules = new Set(); + this.fileToModulesMap.set(file, fileMappedModules); + } + fileMappedModules.add(mod); + } + // multiple urls can map to the same module and id, make sure we register + // the url to the existing module in that case + else if (!this.urlToModuleMap.has(url)) { + this.urlToModuleMap.set(url, mod); + } + return mod; + } + // some deps, like a css file referenced via @import, don't have its own + // url because they are inlined into the main css import. But they still + // need to be represented in the module graph so that they can trigger + // hmr in the importing css file. + createFileOnlyEntry(file) { + file = normalizePath$3(file); + let fileMappedModules = this.fileToModulesMap.get(file); + if (!fileMappedModules) { + fileMappedModules = new Set(); + this.fileToModulesMap.set(file, fileMappedModules); + } + const url = `${FS_PREFIX}${file}`; + for (const m of fileMappedModules) { + if (m.url === url || m.id === file) { + return m; + } + } + const mod = new ModuleNode(url); + mod.file = file; + fileMappedModules.add(mod); + return mod; + } + // for incoming urls, it is important to: + // 1. remove the HMR timestamp query (?t=xxxx) + // 2. resolve its extension so that urls with or without extension all map to + // the same module + async resolveUrl(url, ssr) { + url = removeImportQuery(removeTimestampQuery(url)); + const resolved = await this.resolveId(url, !!ssr); + const resolvedId = resolved?.id || url; + if (url !== resolvedId && + !url.includes('\0') && + !url.startsWith(`virtual:`)) { + const ext = extname$1(cleanUrl(resolvedId)); + const { pathname, search, hash } = new URL(url, 'relative://'); + if (ext && !pathname.endsWith(ext)) { + url = pathname + ext + search + hash; + } + } + return [url, resolvedId, resolved?.meta]; + } +} + +var isWsl$2 = {exports: {}}; + +const fs$3 = require$$0__default; + +let isDocker$2; + +function hasDockerEnv() { + try { + fs$3.statSync('/.dockerenv'); + return true; + } catch (_) { + return false; + } +} + +function hasDockerCGroup() { + try { + return fs$3.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); + } catch (_) { + return false; + } +} + +var isDocker_1 = () => { + if (isDocker$2 === undefined) { + isDocker$2 = hasDockerEnv() || hasDockerCGroup(); + } + + return isDocker$2; +}; + +const os = require$$2; +const fs$2 = require$$0__default; +const isDocker$1 = isDocker_1; + +const isWsl$1 = () => { + if (process.platform !== 'linux') { + return false; + } + + if (os.release().toLowerCase().includes('microsoft')) { + if (isDocker$1()) { + return false; + } + + return true; + } + + try { + return fs$2.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? + !isDocker$1() : false; + } catch (_) { + return false; + } +}; + +if (process.env.__IS_WSL_TEST__) { + isWsl$2.exports = isWsl$1; +} else { + isWsl$2.exports = isWsl$1(); +} + +var defineLazyProp = (object, propertyName, fn) => { + const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true}); + + Object.defineProperty(object, propertyName, { + configurable: true, + enumerable: true, + get() { + const result = fn(); + define(result); + return result; + }, + set(value) { + define(value); + } + }); + + return object; +}; + +const path$3 = require$$0$4; +const childProcess = require$$2$1; +const {promises: fs$1, constants: fsConstants} = require$$0__default; +const isWsl = isWsl$2.exports; +const isDocker = isDocker_1; +const defineLazyProperty = defineLazyProp; + +// Path to included `xdg-open`. +const localXdgOpenPath = path$3.join(__dirname, 'xdg-open'); + +const {platform, arch} = process; + +/** +Get the mount point for fixed drives in WSL. + +@inner +@returns {string} The mount point. +*/ +const getWslDrivesMountPoint = (() => { + // Default value for "root" param + // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config + const defaultMountPoint = '/mnt/'; + + let mountPoint; + + return async function () { + if (mountPoint) { + // Return memoized mount point value + return mountPoint; + } + + const configFilePath = '/etc/wsl.conf'; + + let isConfigFileExists = false; + try { + await fs$1.access(configFilePath, fsConstants.F_OK); + isConfigFileExists = true; + } catch {} + + if (!isConfigFileExists) { + return defaultMountPoint; + } + + const configContent = await fs$1.readFile(configFilePath, {encoding: 'utf8'}); + const configMountPoint = /(?.*)/g.exec(configContent); + + if (!configMountPoint) { + return defaultMountPoint; + } + + mountPoint = configMountPoint.groups.mountPoint.trim(); + mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`; + + return mountPoint; + }; +})(); + +const pTryEach = async (array, mapper) => { + let latestError; + + for (const item of array) { + try { + return await mapper(item); // eslint-disable-line no-await-in-loop + } catch (error) { + latestError = error; + } + } + + throw latestError; +}; + +const baseOpen = async options => { + options = { + wait: false, + background: false, + newInstance: false, + allowNonzeroExitCode: false, + ...options + }; + + if (Array.isArray(options.app)) { + return pTryEach(options.app, singleApp => baseOpen({ + ...options, + app: singleApp + })); + } + + let {name: app, arguments: appArguments = []} = options.app || {}; + appArguments = [...appArguments]; + + if (Array.isArray(app)) { + return pTryEach(app, appName => baseOpen({ + ...options, + app: { + name: appName, + arguments: appArguments + } + })); + } + + let command; + const cliArguments = []; + const childProcessOptions = {}; + + if (platform === 'darwin') { + command = 'open'; + + if (options.wait) { + cliArguments.push('--wait-apps'); + } + + if (options.background) { + cliArguments.push('--background'); + } + + if (options.newInstance) { + cliArguments.push('--new'); + } + + if (app) { + cliArguments.push('-a', app); + } + } else if (platform === 'win32' || (isWsl && !isDocker())) { + const mountPoint = await getWslDrivesMountPoint(); + + command = isWsl ? + `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : + `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; + + cliArguments.push( + '-NoProfile', + '-NonInteractive', + '–ExecutionPolicy', + 'Bypass', + '-EncodedCommand' + ); + + if (!isWsl) { + childProcessOptions.windowsVerbatimArguments = true; + } + + const encodedArguments = ['Start']; + + if (options.wait) { + encodedArguments.push('-Wait'); + } + + if (app) { + // Double quote with double quotes to ensure the inner quotes are passed through. + // Inner quotes are delimited for PowerShell interpretation with backticks. + encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList'); + if (options.target) { + appArguments.unshift(options.target); + } + } else if (options.target) { + encodedArguments.push(`"${options.target}"`); + } + + if (appArguments.length > 0) { + appArguments = appArguments.map(arg => `"\`"${arg}\`""`); + encodedArguments.push(appArguments.join(',')); + } + + // Using Base64-encoded command, accepted by PowerShell, to allow special characters. + options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); + } else { + if (app) { + command = app; + } else { + // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. + const isBundled = !__dirname || __dirname === '/'; + + // Check if local `xdg-open` exists and is executable. + let exeLocalXdgOpen = false; + try { + await fs$1.access(localXdgOpenPath, fsConstants.X_OK); + exeLocalXdgOpen = true; + } catch {} + + const useSystemXdgOpen = process.versions.electron || + platform === 'android' || isBundled || !exeLocalXdgOpen; + command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath; + } + + if (appArguments.length > 0) { + cliArguments.push(...appArguments); + } + + if (!options.wait) { + // `xdg-open` will block the process unless stdio is ignored + // and it's detached from the parent even if it's unref'd. + childProcessOptions.stdio = 'ignore'; + childProcessOptions.detached = true; + } + } + + if (options.target) { + cliArguments.push(options.target); + } + + if (platform === 'darwin' && appArguments.length > 0) { + cliArguments.push('--args', ...appArguments); + } + + const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions); + + if (options.wait) { + return new Promise((resolve, reject) => { + subprocess.once('error', reject); + + subprocess.once('close', exitCode => { + if (options.allowNonzeroExitCode && exitCode > 0) { + reject(new Error(`Exited with code ${exitCode}`)); + return; + } + + resolve(subprocess); + }); + }); + } + + subprocess.unref(); + + return subprocess; +}; + +const open = (target, options) => { + if (typeof target !== 'string') { + throw new TypeError('Expected a `target`'); + } + + return baseOpen({ + ...options, + target + }); +}; + +const openApp = (name, options) => { + if (typeof name !== 'string') { + throw new TypeError('Expected a `name`'); + } + + const {arguments: appArguments = []} = options || {}; + if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) { + throw new TypeError('Expected `appArguments` as Array type'); + } + + return baseOpen({ + ...options, + app: { + name, + arguments: appArguments + } + }); +}; + +function detectArchBinary(binary) { + if (typeof binary === 'string' || Array.isArray(binary)) { + return binary; + } + + const {[arch]: archBinary} = binary; + + if (!archBinary) { + throw new Error(`${arch} is not supported`); + } + + return archBinary; +} + +function detectPlatformBinary({[platform]: platformBinary}, {wsl}) { + if (wsl && isWsl) { + return detectArchBinary(wsl); + } + + if (!platformBinary) { + throw new Error(`${platform} is not supported`); + } + + return detectArchBinary(platformBinary); +} + +const apps = {}; + +defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({ + darwin: 'google chrome', + win32: 'chrome', + linux: ['google-chrome', 'google-chrome-stable', 'chromium'] +}, { + wsl: { + ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe', + x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'] + } +})); + +defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({ + darwin: 'firefox', + win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', + linux: 'firefox' +}, { + wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe' +})); + +defineLazyProperty(apps, 'edge', () => detectPlatformBinary({ + darwin: 'microsoft edge', + win32: 'msedge', + linux: ['microsoft-edge', 'microsoft-edge-dev'] +}, { + wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' +})); + +open.apps = apps; +open.openApp = openApp; + +var open_1 = open; + +var crossSpawn = {exports: {}}; + +var windows; +var hasRequiredWindows; + +function requireWindows () { + if (hasRequiredWindows) return windows; + hasRequiredWindows = 1; + windows = isexe; + isexe.sync = sync; + + var fs = require$$0__default; + + function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT; + + if (!pathext) { + return true + } + + pathext = pathext.split(';'); + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase(); + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false + } + + function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) + } + + function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)); + }); + } + + function sync (path, options) { + return checkStat(fs.statSync(path), path, options) + } + return windows; +} + +var mode; +var hasRequiredMode; + +function requireMode () { + if (hasRequiredMode) return mode; + hasRequiredMode = 1; + mode = isexe; + isexe.sync = sync; + + var fs = require$$0__default; + + function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)); + }); + } + + function sync (path, options) { + return checkStat(fs.statSync(path), options) + } + + function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) + } + + function checkMode (stat, options) { + var mod = stat.mode; + var uid = stat.uid; + var gid = stat.gid; + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid(); + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid(); + + var u = parseInt('100', 8); + var g = parseInt('010', 8); + var o = parseInt('001', 8); + var ug = u | g; + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0; + + return ret + } + return mode; +} + +var core; +if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { + core = requireWindows(); +} else { + core = requireMode(); +} + +var isexe_1 = isexe$1; +isexe$1.sync = sync; + +function isexe$1 (path, options, cb) { + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe$1(path, options || {}, function (er, is) { + if (er) { + reject(er); + } else { + resolve(is); + } + }); + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null; + is = false; + } + } + cb(er, is); + }); +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} + +const isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys'; + +const path$2 = require$$0$4; +const COLON = isWindows ? ';' : ':'; +const isexe = isexe_1; + +const getNotFoundError = (cmd) => + Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); + +const getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON; + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] + : ( + [ + // windows always checks the cwd first + ...(isWindows ? [process.cwd()] : []), + ...(opt.path || process.env.PATH || + /* istanbul ignore next: very unusual */ '').split(colon), + ] + ); + const pathExtExe = isWindows + ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' + : ''; + const pathExt = isWindows ? pathExtExe.split(colon) : ['']; + + if (isWindows) { + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift(''); + } + + return { + pathEnv, + pathExt, + pathExtExe, + } +}; + +const which$1 = (cmd, opt, cb) => { + if (typeof opt === 'function') { + cb = opt; + opt = {}; + } + if (!opt) + opt = {}; + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + + const step = i => new Promise((resolve, reject) => { + if (i === pathEnv.length) + return opt.all && found.length ? resolve(found) + : reject(getNotFoundError(cmd)) + + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + + const pCmd = path$2.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd; + + resolve(subStep(p, i, 0)); + }); + + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i + 1)) + const ext = pathExt[ii]; + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext); + else + return resolve(p + ext) + } + return resolve(subStep(p, i, ii + 1)) + }); + }); + + return cb ? step(0).then(res => cb(null, res), cb) : step(0) +}; + +const whichSync = (cmd, opt) => { + opt = opt || {}; + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + + for (let i = 0; i < pathEnv.length; i ++) { + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + + const pCmd = path$2.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd; + + for (let j = 0; j < pathExt.length; j ++) { + const cur = p + pathExt[j]; + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }); + if (is) { + if (opt.all) + found.push(cur); + else + return cur + } + } catch (ex) {} + } + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) +}; + +var which_1 = which$1; +which$1.sync = whichSync; + +var pathKey$1 = {exports: {}}; + +const pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +pathKey$1.exports = pathKey; +// TODO: Remove this for the next major release +pathKey$1.exports.default = pathKey; + +const path$1 = require$$0$4; +const which = which_1; +const getPathKey = pathKey$1.exports; + +function resolveCommandAttempt(parsed, withoutPathExt) { + const env = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + // Worker threads do not have process.chdir() + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: env[getPathKey({ env })], + pathExt: withoutPathExt ? path$1.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + if (shouldSwitchCwd) { + process.chdir(cwd); + } + } + + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } + + return resolved; +} + +function resolveCommand$1(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} + +var resolveCommand_1 = resolveCommand$1; + +var _escape = {}; + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; +} + +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; + + // Algorithm below is based on https://qntm.org/cmd + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); + + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } + + return arg; +} + +_escape.command = escapeCommand; +_escape.argument = escapeArgument; + +var shebangRegex$1 = /^#!(.*)/; + +const shebangRegex = shebangRegex$1; + +var shebangCommand$1 = (string = '') => { + const match = string.match(shebangRegex); + + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; +}; + +const fs = require$$0__default; +const shebangCommand = shebangCommand$1; + +function readShebang$1(command) { + // Read the first 150 bytes from the file + const size = 150; + const buffer = Buffer.alloc(size); + + let fd; + + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } + + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} + +var readShebang_1 = readShebang$1; + +const path = require$$0$4; +const resolveCommand = resolveCommand_1; +const escape$1 = _escape; +const readShebang = readShebang_1; + +const isWin$1 = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; +} + +function parseNonShell(parsed) { + if (!isWin$1) { + return parsed; + } + + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); + + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); + + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); + + // Escape command & arguments + parsed.command = escape$1.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape$1.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } + + return parsed; +} + +function parse$1(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; + + // Delegate further parsing to shell or non-shell + return options.shell ? parsed : parseNonShell(parsed); +} + +var parse_1 = parse$1; + +const isWin = process.platform === 'win32'; + +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); +} + +function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed); + + if (err) { + return originalEmit.call(cp, 'error', err); + } + } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; +} + +function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; +} + +function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } + + return null; +} + +var enoent$1 = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; + +const cp = require$$2$1; +const parse = parse_1; +const enoent = enoent$1; + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; +} + +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; +} + +crossSpawn.exports = spawn; +crossSpawn.exports.spawn = spawn; +crossSpawn.exports.sync = spawnSync; + +crossSpawn.exports._parse = parse; +crossSpawn.exports._enoent = enoent; + +/** + * The following is modified based on source found in + * https://github.com/facebook/create-react-app + * + * MIT Licensed + * Copyright (c) 2015-present, Facebook, Inc. + * https://github.com/facebook/create-react-app/blob/master/LICENSE + * + */ +/** + * Reads the BROWSER environment variable and decides what to do with it. + * Returns true if it opened a browser or ran a node.js script, otherwise false. + */ +function openBrowser(url, opt, logger) { + // The browser executable to open. + // See https://github.com/sindresorhus/open#app for documentation. + const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''; + if (browser.toLowerCase().endsWith('.js')) { + return executeNodeScript(browser, url, logger); + } + else if (browser.toLowerCase() !== 'none') { + return startBrowserProcess(browser, url); + } + return false; +} +function executeNodeScript(scriptPath, url, logger) { + const extraArgs = process.argv.slice(2); + const child = crossSpawn.exports(process.execPath, [scriptPath, ...extraArgs, url], { + stdio: 'inherit' + }); + child.on('close', (code) => { + if (code !== 0) { + logger.error(picocolors.exports.red(`\nThe script specified as BROWSER environment variable failed.\n\n${picocolors.exports.cyan(scriptPath)} exited with code ${code}.`), { error: null }); + } + }); + return true; +} +const supportedChromiumBrowsers = [ + 'Google Chrome Canary', + 'Google Chrome Dev', + 'Google Chrome Beta', + 'Google Chrome', + 'Microsoft Edge', + 'Brave Browser', + 'Vivaldi', + 'Chromium' +]; +function startBrowserProcess(browser, url) { + // If we're on OS X, the user hasn't specifically + // requested a different browser, we can try opening + // a Chromium browser with AppleScript. This lets us reuse an + // existing tab when possible instead of creating a new one. + const preferredOSXBrowser = browser === 'google chrome' ? 'Google Chrome' : browser; + const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && + (!preferredOSXBrowser || + supportedChromiumBrowsers.includes(preferredOSXBrowser)); + if (shouldTryOpenChromeWithAppleScript) { + try { + const ps = execSync('ps cax').toString(); + const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser) + ? preferredOSXBrowser + : supportedChromiumBrowsers.find((b) => ps.includes(b)); + // Try our best to reuse existing tab with AppleScript + execSync(`osascript openChrome.applescript "${encodeURI(url)}" "${openedBrowser}"`, { + cwd: join$2(VITE_PACKAGE_DIR, 'bin'), + stdio: 'ignore' + }); + return true; + } + catch (err) { + // Ignore errors + } + } + // Another special case: on OS X, check if BROWSER has been set to "open". + // In this case, instead of passing the string `open` to `open` function (which won't work), + // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser): + // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768 + if (process.platform === 'darwin' && browser === 'open') { + browser = undefined; + } + // Fallback to open + // (It will always open new tab) + try { + const options = browser ? { app: { name: browser } } : {}; + open_1(url, options).catch(() => { }); // Prevent `unhandledRejection` error. + return true; + } + catch (err) { + return false; + } +} + +async function createServer(inlineConfig = {}) { + const config = await resolveConfig(inlineConfig, 'serve', 'development'); + const { root, server: serverConfig } = config; + const httpsOptions = await resolveHttpsConfig(config.server.https); + const { middlewareMode } = serverConfig; + const resolvedWatchOptions = resolveChokidarOptions({ + disableGlobbing: true, + ...serverConfig.watch + }); + const middlewares = connect(); + const httpServer = middlewareMode + ? null + : await resolveHttpServer(serverConfig, middlewares, httpsOptions); + const ws = createWebSocketServer(httpServer, config, httpsOptions); + if (httpServer) { + setClientErrorHandler(httpServer, config.logger); + } + const watcher = chokidar.watch(path$o.resolve(root), resolvedWatchOptions); + const moduleGraph = new ModuleGraph((url, ssr) => container.resolveId(url, undefined, { ssr })); + const container = await createPluginContainer(config, moduleGraph, watcher); + const closeHttpServer = createServerCloseFn(httpServer); + let exitProcess; + const server = { + config, + middlewares, + httpServer, + watcher, + pluginContainer: container, + ws, + moduleGraph, + resolvedUrls: null, + ssrTransform(code, inMap, url, originalCode = code) { + return ssrTransform(code, inMap, url, originalCode, server.config); + }, + transformRequest(url, options) { + return transformRequest(url, server, options); + }, + transformIndexHtml: null, + async ssrLoadModule(url, opts) { + if (isDepsOptimizerEnabled(config, true)) { + await initDevSsrDepsOptimizer(config, server); + } + await updateCjsSsrExternals(server); + return ssrLoadModule(url, server, undefined, undefined, opts?.fixStacktrace); + }, + ssrFixStacktrace(e) { + if (e.stack) { + const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph); + rebindErrorStacktrace(e, stacktrace); + } + }, + ssrRewriteStacktrace(stack) { + return ssrRewriteStacktrace(stack, moduleGraph); + }, + async reloadModule(module) { + if (serverConfig.hmr !== false && module.file) { + updateModules(module.file, [module], Date.now(), server); + } + }, + async listen(port, isRestart) { + await startServer(server, port, isRestart); + if (httpServer) { + server.resolvedUrls = await resolveServerUrls(httpServer, config.server, config); + } + return server; + }, + async close() { + if (!middlewareMode) { + process.off('SIGTERM', exitProcess); + if (process.env.CI !== 'true') { + process.stdin.off('end', exitProcess); + } + } + await Promise.all([ + watcher.close(), + ws.close(), + container.close(), + getDepsOptimizer(server.config)?.close(), + getDepsOptimizer(server.config, true)?.close(), + closeHttpServer() + ]); + server.resolvedUrls = null; + }, + printUrls() { + if (server.resolvedUrls) { + printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info); + } + else if (middlewareMode) { + throw new Error('cannot print server URLs in middleware mode.'); + } + else { + throw new Error('cannot print server URLs before server.listen is called.'); + } + }, + async restart(forceOptimize) { + if (!server._restartPromise) { + server._forceOptimizeOnRestart = !!forceOptimize; + server._restartPromise = restartServer(server).finally(() => { + server._restartPromise = null; + server._forceOptimizeOnRestart = false; + }); + } + return server._restartPromise; + }, + _ssrExternals: null, + _restartPromise: null, + _importGlobMap: new Map(), + _forceOptimizeOnRestart: false, + _pendingRequests: new Map(), + _fsDenyGlob: picomatch$3(config.server.fs.deny, { matchBase: true }) + }; + server.transformIndexHtml = createDevHtmlTransformFn(server); + if (!middlewareMode) { + exitProcess = async () => { + try { + await server.close(); + } + finally { + process.exit(); + } + }; + process.once('SIGTERM', exitProcess); + if (process.env.CI !== 'true') { + process.stdin.on('end', exitProcess); + } + } + const { packageCache } = config; + const setPackageData = packageCache.set.bind(packageCache); + packageCache.set = (id, pkg) => { + if (id.endsWith('.json')) { + watcher.add(id); + } + return setPackageData(id, pkg); + }; + watcher.on('change', async (file) => { + file = normalizePath$3(file); + if (file.endsWith('/package.json')) { + return invalidatePackageData(packageCache, file); + } + // invalidate module graph cache on file change + moduleGraph.onFileChange(file); + if (serverConfig.hmr !== false) { + try { + await handleHMRUpdate(file, server); + } + catch (err) { + ws.send({ + type: 'error', + err: prepareError(err) + }); + } + } + }); + watcher.on('add', (file) => { + handleFileAddUnlink(normalizePath$3(file), server); + }); + watcher.on('unlink', (file) => { + handleFileAddUnlink(normalizePath$3(file), server); + }); + ws.on('vite:invalidate', async ({ path }) => { + const mod = moduleGraph.urlToModuleMap.get(path); + if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) { + const file = getShortName(mod.file, config.root); + updateModules(file, [...mod.importers], mod.lastHMRTimestamp, server); + } + }); + if (!middlewareMode && httpServer) { + httpServer.once('listening', () => { + // update actual port since this may be different from initial value + serverConfig.port = httpServer.address().port; + }); + } + // apply server configuration hooks from plugins + const postHooks = []; + for (const hook of config.getSortedPluginHooks('configureServer')) { + postHooks.push(await hook(server)); + } + // Internal middlewares ------------------------------------------------------ + // request timer + if (process.env.DEBUG) { + middlewares.use(timeMiddleware(root)); + } + // cors (enabled by default) + const { cors } = serverConfig; + if (cors !== false) { + middlewares.use(lib$1.exports(typeof cors === 'boolean' ? {} : cors)); + } + // proxy + const { proxy } = serverConfig; + if (proxy) { + middlewares.use(proxyMiddleware(httpServer, proxy, config)); + } + // base + if (config.base !== '/') { + middlewares.use(baseMiddleware(server)); + } + // open in editor support + middlewares.use('/__open-in-editor', launchEditorMiddleware()); + // serve static files under /public + // this applies before the transform middleware so that these files are served + // as-is without transforms. + if (config.publicDir) { + middlewares.use(servePublicMiddleware(config.publicDir, config.server.headers)); + } + // main transform middleware + middlewares.use(transformMiddleware(server)); + // serve static files + middlewares.use(serveRawFsMiddleware(server)); + middlewares.use(serveStaticMiddleware(root, server)); + // html fallback + if (config.appType === 'spa' || config.appType === 'mpa') { + middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa')); + } + // run post config hooks + // This is applied before the html middleware so that user middleware can + // serve custom content instead of index.html. + postHooks.forEach((fn) => fn && fn()); + if (config.appType === 'spa' || config.appType === 'mpa') { + // transform index.html + middlewares.use(indexHtmlMiddleware(server)); + // handle 404s + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + middlewares.use(function vite404Middleware(_, res) { + res.statusCode = 404; + res.end(); + }); + } + // error handler + middlewares.use(errorMiddleware(server, middlewareMode)); + let initingServer; + let serverInited = false; + const initServer = async () => { + if (serverInited) { + return; + } + if (initingServer) { + return initingServer; + } + initingServer = (async function () { + await container.buildStart({}); + if (isDepsOptimizerEnabled(config, false)) { + // non-ssr + await initDepsOptimizer(config, server); + } + initingServer = undefined; + serverInited = true; + })(); + return initingServer; + }; + if (!middlewareMode && httpServer) { + // overwrite listen to init optimizer before server start + const listen = httpServer.listen.bind(httpServer); + httpServer.listen = (async (port, ...args) => { + try { + await initServer(); + } + catch (e) { + httpServer.emit('error', e); + return; + } + return listen(port, ...args); + }); + } + else { + await initServer(); + } + return server; +} +async function startServer(server, inlinePort, isRestart = false) { + const httpServer = server.httpServer; + if (!httpServer) { + throw new Error('Cannot call server.listen in middleware mode.'); + } + const options = server.config.server; + const port = inlinePort ?? options.port ?? 5173; + const hostname = await resolveHostname(options.host); + const protocol = options.https ? 'https' : 'http'; + const info = server.config.logger.info; + const serverPort = await httpServerStart(httpServer, { + port, + strictPort: options.strictPort, + host: hostname.host, + logger: server.config.logger + }); + // @ts-ignore + const profileSession = global.__vite_profile_session; + if (profileSession) { + profileSession.post('Profiler.stop', (err, { profile }) => { + // Write profile to disk, upload, etc. + if (!err) { + const outPath = path$o.resolve('./vite-profile.cpuprofile'); + fs$l.writeFileSync(outPath, JSON.stringify(profile)); + info(picocolors.exports.yellow(` CPU profile written to ${picocolors.exports.white(picocolors.exports.dim(outPath))}\n`)); + } + else { + throw err; + } + }); + } + if (options.open && !isRestart) { + const path = typeof options.open === 'string' ? options.open : server.config.base; + openBrowser(path.startsWith('http') + ? path + : `${protocol}://${hostname.name}:${serverPort}${path}`, true, server.config.logger); + } +} +function createServerCloseFn(server) { + if (!server) { + return () => { }; + } + let hasListened = false; + const openSockets = new Set(); + server.on('connection', (socket) => { + openSockets.add(socket); + socket.on('close', () => { + openSockets.delete(socket); + }); + }); + server.once('listening', () => { + hasListened = true; + }); + return () => new Promise((resolve, reject) => { + openSockets.forEach((s) => s.destroy()); + if (hasListened) { + server.close((err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + } + else { + resolve(); + } + }); +} +function resolvedAllowDir(root, dir) { + return normalizePath$3(path$o.resolve(root, dir)); +} +function resolveServerOptions(root, raw, logger) { + const server = { + preTransformRequests: true, + ...raw, + middlewareMode: !!raw?.middlewareMode + }; + let allowDirs = server.fs?.allow; + const deny = server.fs?.deny || ['.env', '.env.*', '*.{crt,pem}']; + if (!allowDirs) { + allowDirs = [searchForWorkspaceRoot(root)]; + } + allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i)); + // only push client dir when vite itself is outside-of-root + const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR); + if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) { + allowDirs.push(resolvedClientDir); + } + server.fs = { + strict: server.fs?.strict ?? true, + allow: allowDirs, + deny + }; + if (server.origin?.endsWith('/')) { + server.origin = server.origin.slice(0, -1); + logger.warn(picocolors.exports.yellow(`${picocolors.exports.bold('(!)')} server.origin should not end with "/". Using "${server.origin}" instead.`)); + } + return server; +} +async function restartServer(server) { + // @ts-ignore + global.__vite_start_time = performance.now(); + const { port: prevPort, host: prevHost } = server.config.server; + await server.close(); + let inlineConfig = server.config.inlineConfig; + if (server._forceOptimizeOnRestart) { + inlineConfig = mergeConfig(inlineConfig, { + optimizeDeps: { + force: true + } + }); + } + let newServer = null; + try { + newServer = await createServer(inlineConfig); + } + catch (err) { + server.config.logger.error(err.message, { + timestamp: true + }); + return; + } + for (const key in newServer) { + if (key === '_restartPromise') { + // prevent new server `restart` function from calling + // @ts-ignore + newServer[key] = server[key]; + } + else { + // @ts-ignore + server[key] = newServer[key]; + } + } + const { logger, server: { port, host, middlewareMode } } = server.config; + if (!middlewareMode) { + await server.listen(port, true); + logger.info('server restarted.', { timestamp: true }); + if (port !== prevPort || host !== prevHost) { + logger.info(''); + server.printUrls(); + } + } + else { + logger.info('server restarted.', { timestamp: true }); + } + // new server (the current server) can restart now + newServer._restartPromise = null; +} +async function updateCjsSsrExternals(server) { + if (!server._ssrExternals) { + let knownImports = []; + // Important! We use the non-ssr optimized deps to find known imports + // Only the explicitly defined deps are optimized during dev SSR, so + // we use the generated list from the scanned deps in regular dev. + // This is part of the v2 externalization heuristics and it is kept + // for backwards compatibility in case user needs to fallback to the + // legacy scheme. It may be removed in a future v3 minor. + const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr + if (depsOptimizer) { + await depsOptimizer.scanProcessing; + knownImports = [ + ...Object.keys(depsOptimizer.metadata.optimized), + ...Object.keys(depsOptimizer.metadata.discovered) + ]; + } + server._ssrExternals = cjsSsrResolveExternals(server.config, knownImports); + } +} + +var index = { + __proto__: null, + createServer: createServer, + resolveServerOptions: resolveServerOptions, + searchForWorkspaceRoot: searchForWorkspaceRoot +}; + +//@ts-nocheck +/* global Buffer */ +const noop = () => { }; +const mimes = /text|javascript|\/json|xml/i; +const threshold = 1024; +const level = -1; +let brotli = false; +const getChunkSize = (chunk, enc) => (chunk ? Buffer.byteLength(chunk, enc) : 0); +function compression() { + const brotliOpts = (typeof brotli === 'object' && brotli) || {}; + const gzipOpts = {}; + // disable Brotli on Node<12.7 where it is unsupported: + if (!zlib$1.createBrotliCompress) + brotli = false; + return (req, res, next = noop) => { + const accept = req.headers['accept-encoding'] + ''; + const encoding = ((brotli && accept.match(/\bbr\b/)) || + (accept.match(/\bgzip\b/)) || + [])[0]; + // skip if no response body or no supported encoding: + if (req.method === 'HEAD' || !encoding) + return next(); + /** @type {zlib.Gzip | zlib.BrotliCompress} */ + let compress; + let pendingStatus; + /** @type {[string, function][]?} */ + let pendingListeners = []; + let started = false; + let size = 0; + function start() { + started = true; + // @ts-ignore + size = res.getHeader('Content-Length') | 0 || size; + const compressible = mimes.test(String(res.getHeader('Content-Type') || 'text/plain')); + const cleartext = !res.getHeader('Content-Encoding'); + const listeners = pendingListeners || []; + if (compressible && cleartext && size >= threshold) { + res.setHeader('Content-Encoding', encoding); + res.removeHeader('Content-Length'); + if (encoding === 'br') { + const params = { + [zlib$1.constants.BROTLI_PARAM_QUALITY]: level, + [zlib$1.constants.BROTLI_PARAM_SIZE_HINT]: size + }; + compress = zlib$1.createBrotliCompress({ + params: Object.assign(params, brotliOpts) + }); + } + else { + compress = zlib$1.createGzip(Object.assign({ level }, gzipOpts)); + } + // backpressure + compress.on('data', (chunk) => write.call(res, chunk) === false && compress.pause()); + on.call(res, 'drain', () => compress.resume()); + compress.on('end', () => end.call(res)); + listeners.forEach((p) => compress.on.apply(compress, p)); + } + else { + pendingListeners = null; + listeners.forEach((p) => on.apply(res, p)); + } + writeHead.call(res, pendingStatus || res.statusCode); + } + const { end, write, on, writeHead } = res; + res.writeHead = function (status, reason, headers) { + if (typeof reason !== 'string') + [headers, reason] = [reason, headers]; + if (headers) + for (let i in headers) + res.setHeader(i, headers[i]); + pendingStatus = status; + return this; + }; + res.write = function (chunk, enc, cb) { + size += getChunkSize(chunk, enc); + if (!started) + start(); + if (!compress) + return write.apply(this, arguments); + return compress.write.apply(compress, arguments); + }; + res.end = function (chunk, enc, cb) { + if (arguments.length > 0 && typeof chunk !== 'function') { + size += getChunkSize(chunk, enc); + } + if (!started) + start(); + if (!compress) + return end.apply(this, arguments); + return compress.end.apply(compress, arguments); + }; + res.on = function (type, listener) { + if (!pendingListeners || type !== 'drain') + on.call(this, type, listener); + else if (compress) + compress.on(type, listener); + else + pendingListeners.push([type, listener]); + return this; + }; + next(); + }; +} + +function resolvePreviewOptions(preview, server) { + // The preview server inherits every CommonServerOption from the `server` config + // except for the port to enable having both the dev and preview servers running + // at the same time without extra configuration + return { + port: preview?.port, + strictPort: preview?.strictPort ?? server.strictPort, + host: preview?.host ?? server.host, + https: preview?.https ?? server.https, + open: preview?.open ?? server.open, + proxy: preview?.proxy ?? server.proxy, + cors: preview?.cors ?? server.cors, + headers: preview?.headers ?? server.headers + }; +} +/** + * Starts the Vite server in preview mode, to simulate a production deployment + */ +async function preview(inlineConfig = {}) { + const config = await resolveConfig(inlineConfig, 'serve', 'production'); + const app = connect(); + const httpServer = await resolveHttpServer(config.preview, app, await resolveHttpsConfig(config.preview?.https)); + setClientErrorHandler(httpServer, config.logger); + // apply server hooks from plugins + const postHooks = []; + for (const hook of config.getSortedPluginHooks('configurePreviewServer')) { + postHooks.push(await hook({ middlewares: app, httpServer })); + } + // cors + const { cors } = config.preview; + if (cors !== false) { + app.use(lib$1.exports(typeof cors === 'boolean' ? {} : cors)); + } + // proxy + const { proxy } = config.preview; + if (proxy) { + app.use(proxyMiddleware(httpServer, proxy, config)); + } + app.use(compression()); + const previewBase = config.base === './' || config.base === '' ? '/' : config.base; + // static assets + const distDir = path$o.resolve(config.root, config.build.outDir); + const headers = config.preview.headers; + app.use(previewBase, sirv(distDir, { + etag: true, + dev: true, + single: config.appType === 'spa', + setHeaders(res) { + if (headers) { + for (const name in headers) { + res.setHeader(name, headers[name]); + } + } + } + })); + // apply post server hooks from plugins + postHooks.forEach((fn) => fn && fn()); + const options = config.preview; + const hostname = await resolveHostname(options.host); + const port = options.port ?? 4173; + const protocol = options.https ? 'https' : 'http'; + const logger = config.logger; + const serverPort = await httpServerStart(httpServer, { + port, + strictPort: options.strictPort, + host: hostname.host, + logger + }); + const resolvedUrls = await resolveServerUrls(httpServer, config.preview, config); + if (options.open) { + const path = typeof options.open === 'string' ? options.open : previewBase; + openBrowser(path.startsWith('http') + ? path + : `${protocol}://${hostname.name}:${serverPort}${path}`, true, logger); + } + return { + config, + httpServer, + resolvedUrls, + printUrls() { + printServerUrls(resolvedUrls, options.host, logger.info); + } + }; +} + +var preview$1 = { + __proto__: null, + resolvePreviewOptions: resolvePreviewOptions, + preview: preview +}; + +function resolveSSROptions(ssr, preserveSymlinks, buildSsrCjsExternalHeuristics) { + ssr ?? (ssr = {}); + const optimizeDeps = ssr.optimizeDeps ?? {}; + let format = 'esm'; + let target = 'node'; + if (buildSsrCjsExternalHeuristics) { + if (ssr) { + format = 'cjs'; + } + else { + target = 'node'; + format = 'cjs'; + } + } + return { + format, + target, + ...ssr, + optimizeDeps: { + disabled: true, + ...optimizeDeps, + esbuildOptions: { + preserveSymlinks, + ...optimizeDeps.esbuildOptions + } + } + }; +} + +const debug = createDebugger('vite:config'); +/** + * Type helper to make it easier to use vite.config.ts + * accepts a direct {@link UserConfig} object, or a function that returns it. + * The function receives a {@link ConfigEnv} object that exposes two properties: + * `command` (either `'build'` or `'serve'`), and `mode`. + */ +function defineConfig(config) { + return config; +} +async function resolveConfig(inlineConfig, command, defaultMode = 'development') { + let config = inlineConfig; + let configFileDependencies = []; + let mode = inlineConfig.mode || defaultMode; + // some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting + // production-specific behavior, so set it here even though we haven't + // resolve the final mode yet + if (mode === 'production') { + process.env.NODE_ENV = 'production'; + } + // production env would not work in serve, fallback to development + if (command === 'serve' && process.env.NODE_ENV === 'production') { + process.env.NODE_ENV = 'development'; + } + const configEnv = { + mode, + command, + ssrBuild: !!config.build?.ssr + }; + let { configFile } = config; + if (configFile !== false) { + const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel); + if (loadResult) { + config = mergeConfig(loadResult.config, config); + configFile = loadResult.path; + configFileDependencies = loadResult.dependencies; + } + } + // user config may provide an alternative mode. But --mode has a higher priority + mode = inlineConfig.mode || config.mode || mode; + configEnv.mode = mode; + const filterPlugin = (p) => { + if (!p) { + return false; + } + else if (!p.apply) { + return true; + } + else if (typeof p.apply === 'function') { + return p.apply({ ...config, mode }, configEnv); + } + else { + return p.apply === command; + } + }; + // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example). + // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls. + // So we need to separate the worker plugin from the plugin that vite needs to run. + const rawWorkerUserPlugins = (await asyncFlatten(config.worker?.plugins || [])).filter(filterPlugin); + // resolve plugins + const rawUserPlugins = (await asyncFlatten(config.plugins || [])).filter(filterPlugin); + const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins); + // run config hooks + const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins]; + config = await runConfigHook(config, userPlugins, configEnv); + if (process.env.VITE_TEST_WITHOUT_PLUGIN_COMMONJS) { + config = mergeConfig(config, { + optimizeDeps: { disabled: false }, + ssr: { optimizeDeps: { disabled: false } } + }); + config.build ?? (config.build = {}); + config.build.commonjsOptions = { include: [] }; + } + // Define logger + const logger = createLogger(config.logLevel, { + allowClearScreen: config.clearScreen, + customLogger: config.customLogger + }); + // resolve root + const resolvedRoot = normalizePath$3(config.root ? path$o.resolve(config.root) : process.cwd()); + const clientAlias = [ + { find: /^[\/]?@vite\/env/, replacement: () => ENV_ENTRY }, + { find: /^[\/]?@vite\/client/, replacement: () => CLIENT_ENTRY } + ]; + // resolve alias with internal client alias + const resolvedAlias = normalizeAlias(mergeAlias( + // @ts-ignore because @rollup/plugin-alias' type doesn't allow function + // replacement, but its implementation does work with function values. + clientAlias, config.resolve?.alias || [])); + const resolveOptions = { + mainFields: config.resolve?.mainFields ?? DEFAULT_MAIN_FIELDS, + browserField: config.resolve?.browserField ?? true, + conditions: config.resolve?.conditions ?? [], + extensions: config.resolve?.extensions ?? DEFAULT_EXTENSIONS$1, + dedupe: config.resolve?.dedupe ?? [], + preserveSymlinks: config.resolve?.preserveSymlinks ?? false, + alias: resolvedAlias + }; + // load .env files + const envDir = config.envDir + ? normalizePath$3(path$o.resolve(resolvedRoot, config.envDir)) + : resolvedRoot; + const userEnv = inlineConfig.envFile !== false && + loadEnv(mode, envDir, resolveEnvPrefix(config)); + // Note it is possible for user to have a custom mode, e.g. `staging` where + // production-like behavior is expected. This is indicated by NODE_ENV=production + // loaded from `.staging.env` and set by us as VITE_USER_NODE_ENV + const isProduction = (process.env.NODE_ENV || process.env.VITE_USER_NODE_ENV || mode) === + 'production'; + if (isProduction) { + // in case default mode was not production and is overwritten + process.env.NODE_ENV = 'production'; + } + // resolve public base url + const isBuild = command === 'build'; + const relativeBaseShortcut = config.base === '' || config.base === './'; + // During dev, we ignore relative base and fallback to '/' + // For the SSR build, relative base isn't possible by means + // of import.meta.url. + const resolvedBase = relativeBaseShortcut + ? !isBuild || config.build?.ssr + ? '/' + : './' + : resolveBaseUrl(config.base, isBuild, logger) ?? '/'; + const resolvedBuildOptions = resolveBuildOptions(config.build, logger); + // resolve cache directory + const pkgPath = lookupFile(resolvedRoot, [`package.json`], { pathOnly: true }); + const cacheDir = config.cacheDir + ? path$o.resolve(resolvedRoot, config.cacheDir) + : pkgPath + ? path$o.join(path$o.dirname(pkgPath), `node_modules/.vite`) + : path$o.join(resolvedRoot, `.vite`); + const assetsFilter = config.assetsInclude && + (!(config.assetsInclude instanceof Array) || config.assetsInclude.length) + ? createFilter(config.assetsInclude) + : () => false; + // create an internal resolver to be used in special scenarios, e.g. + // optimizer & handling css @imports + const createResolver = (options) => { + let aliasContainer; + let resolverContainer; + return async (id, importer, aliasOnly, ssr) => { + let container; + if (aliasOnly) { + container = + aliasContainer || + (aliasContainer = await createPluginContainer({ + ...resolved, + plugins: [alias$1({ entries: resolved.resolve.alias })] + })); + } + else { + container = + resolverContainer || + (resolverContainer = await createPluginContainer({ + ...resolved, + plugins: [ + alias$1({ entries: resolved.resolve.alias }), + resolvePlugin({ + ...resolved.resolve, + root: resolvedRoot, + isProduction, + isBuild: command === 'build', + ssrConfig: resolved.ssr, + asSrc: true, + preferRelative: false, + tryIndex: true, + ...options + }) + ] + })); + } + return (await container.resolveId(id, importer, { ssr, scan: options?.scan }))?.id; + }; + }; + const { publicDir } = config; + const resolvedPublicDir = publicDir !== false && publicDir !== '' + ? path$o.resolve(resolvedRoot, typeof publicDir === 'string' ? publicDir : 'public') + : ''; + const server = resolveServerOptions(resolvedRoot, config.server, logger); + const ssr = resolveSSROptions(config.ssr, resolveOptions.preserveSymlinks, config.legacy?.buildSsrCjsExternalHeuristics); + const middlewareMode = config?.server?.middlewareMode; + const optimizeDeps = config.optimizeDeps || {}; + const BASE_URL = resolvedBase; + // resolve worker + let workerConfig = mergeConfig({}, config); + const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins); + // run config hooks + const workerUserPlugins = [ + ...workerPrePlugins, + ...workerNormalPlugins, + ...workerPostPlugins + ]; + workerConfig = await runConfigHook(workerConfig, workerUserPlugins, configEnv); + const resolvedWorkerOptions = { + format: workerConfig.worker?.format || 'iife', + plugins: [], + rollupOptions: workerConfig.worker?.rollupOptions || {}, + getSortedPlugins: undefined, + getSortedPluginHooks: undefined + }; + const resolvedConfig = { + configFile: configFile ? normalizePath$3(configFile) : undefined, + configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$o.resolve(name))), + inlineConfig, + root: resolvedRoot, + base: resolvedBase, + resolve: resolveOptions, + publicDir: resolvedPublicDir, + cacheDir, + command, + mode, + ssr, + isWorker: false, + mainConfig: null, + isProduction, + plugins: userPlugins, + server, + build: resolvedBuildOptions, + preview: resolvePreviewOptions(config.preview, server), + env: { + ...userEnv, + BASE_URL, + MODE: mode, + DEV: !isProduction, + PROD: isProduction + }, + assetsInclude(file) { + return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file); + }, + logger, + packageCache: new Map(), + createResolver, + optimizeDeps: { + disabled: 'build', + ...optimizeDeps, + esbuildOptions: { + preserveSymlinks: resolveOptions.preserveSymlinks, + ...optimizeDeps.esbuildOptions + } + }, + worker: resolvedWorkerOptions, + appType: config.appType ?? (middlewareMode === 'ssr' ? 'custom' : 'spa'), + experimental: { + importGlobRestoreExtension: false, + hmrPartialAccept: false, + ...config.experimental + }, + getSortedPlugins: undefined, + getSortedPluginHooks: undefined + }; + const resolved = { + ...config, + ...resolvedConfig + }; + resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins); + Object.assign(resolved, createPluginHookUtils(resolved.plugins)); + const workerResolved = { + ...workerConfig, + ...resolvedConfig, + isWorker: true, + mainConfig: resolved + }; + resolvedConfig.worker.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins); + Object.assign(resolvedConfig.worker, createPluginHookUtils(resolvedConfig.worker.plugins)); + // call configResolved hooks + await Promise.all([ + ...resolved + .getSortedPluginHooks('configResolved') + .map((hook) => hook(resolved)), + ...resolvedConfig.worker + .getSortedPluginHooks('configResolved') + .map((hook) => hook(workerResolved)) + ]); + // validate config + if (middlewareMode === 'ssr') { + logger.warn(picocolors.exports.yellow(`Setting server.middlewareMode to 'ssr' is deprecated, set server.middlewareMode to \`true\`${config.appType === 'custom' ? '' : ` and appType to 'custom'`} instead`)); + } + if (middlewareMode === 'html') { + logger.warn(picocolors.exports.yellow(`Setting server.middlewareMode to 'html' is deprecated, set server.middlewareMode to \`true\` instead`)); + } + if (config.server?.force && + !isBuild && + config.optimizeDeps?.force === undefined) { + resolved.optimizeDeps.force = true; + logger.warn(picocolors.exports.yellow(`server.force is deprecated, use optimizeDeps.force instead`)); + } + if (process.env.DEBUG) { + debug(`using resolved config: %O`, { + ...resolved, + plugins: resolved.plugins.map((p) => p.name), + worker: { + ...resolved.worker, + plugins: resolved.worker.plugins.map((p) => p.name) + } + }); + } + if (config.build?.terserOptions && config.build.minify !== 'terser') { + logger.warn(picocolors.exports.yellow(`build.terserOptions is specified but build.minify is not set to use Terser. ` + + `Note Vite now defaults to use esbuild for minification. If you still ` + + `prefer Terser, set build.minify to "terser".`)); + } + // Check if all assetFileNames have the same reference. + // If not, display a warn for user. + const outputOption = config.build?.rollupOptions?.output ?? []; + // Use isArray to narrow its type to array + if (Array.isArray(outputOption)) { + const assetFileNamesList = outputOption.map((output) => output.assetFileNames); + if (assetFileNamesList.length > 1) { + const firstAssetFileNames = assetFileNamesList[0]; + const hasDifferentReference = assetFileNamesList.some((assetFileNames) => assetFileNames !== firstAssetFileNames); + if (hasDifferentReference) { + resolved.logger.warn(picocolors.exports.yellow(` +assetFileNames isn't equal for every build.rollupOptions.output. A single pattern across all outputs is supported by Vite. +`)); + } + } + } + return resolved; +} +/** + * Resolve base url. Note that some users use Vite to build for non-web targets like + * electron or expects to deploy + */ +function resolveBaseUrl(base = '/', isBuild, logger) { + if (base.startsWith('.')) { + logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` + + `URL, ./, or an empty string.`))); + base = '/'; + } + // external URL + if (isExternalUrl(base)) { + if (!isBuild) { + // get base from full url during dev + const parsed = parse$j(base); + base = parsed.pathname || '/'; + } + } + else { + // ensure leading slash + if (!base.startsWith('/')) { + logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) "base" option should start with a slash.`))); + base = '/' + base; + } + } + // ensure ending slash + if (!base.endsWith('/')) { + logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) "base" option should end with a slash.`))); + base += '/'; + } + return base; +} +function sortUserPlugins(plugins) { + const prePlugins = []; + const postPlugins = []; + const normalPlugins = []; + if (plugins) { + plugins.flat().forEach((p) => { + if (p.enforce === 'pre') + prePlugins.push(p); + else if (p.enforce === 'post') + postPlugins.push(p); + else + normalPlugins.push(p); + }); + } + return [prePlugins, normalPlugins, postPlugins]; +} +async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel) { + const start = performance.now(); + const getTime = () => `${(performance.now() - start).toFixed(2)}ms`; + let resolvedPath; + if (configFile) { + // explicit config path is always resolved from cwd + resolvedPath = path$o.resolve(configFile); + } + else { + // implicit config file loaded from inline root (if present) + // otherwise from cwd + for (const filename of DEFAULT_CONFIG_FILES) { + const filePath = path$o.resolve(configRoot, filename); + if (!fs$l.existsSync(filePath)) + continue; + resolvedPath = filePath; + break; + } + } + if (!resolvedPath) { + debug('no config file found.'); + return null; + } + let isESM = false; + if (/\.m[jt]s$/.test(resolvedPath)) { + isESM = true; + } + else if (/\.c[jt]s$/.test(resolvedPath)) { + isESM = false; + } + else { + // check package.json for type: "module" and set `isESM` to true + try { + const pkg = lookupFile(configRoot, ['package.json']); + isESM = !!pkg && JSON.parse(pkg).type === 'module'; + } + catch (e) { } + } + try { + const bundled = await bundleConfigFile(resolvedPath, isESM); + const userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM); + debug(`bundled config file loaded in ${getTime()}`); + const config = await (typeof userConfig === 'function' + ? userConfig(configEnv) + : userConfig); + if (!isObject$1(config)) { + throw new Error(`config must export or return an object.`); + } + return { + path: normalizePath$3(resolvedPath), + config, + dependencies: bundled.dependencies + }; + } + catch (e) { + createLogger(logLevel).error(picocolors.exports.red(`failed to load config from ${resolvedPath}`), { error: e }); + throw e; + } +} +async function bundleConfigFile(fileName, isESM) { + const dirnameVarName = '__vite_injected_original_dirname'; + const filenameVarName = '__vite_injected_original_filename'; + const importMetaUrlVarName = '__vite_injected_original_import_meta_url'; + const result = await build$3({ + absWorkingDir: process.cwd(), + entryPoints: [fileName], + outfile: 'out.js', + write: false, + target: ['node14.18', 'node16'], + platform: 'node', + bundle: true, + format: isESM ? 'esm' : 'cjs', + mainFields: ['main'], + sourcemap: 'inline', + metafile: true, + define: { + __dirname: dirnameVarName, + __filename: filenameVarName, + 'import.meta.url': importMetaUrlVarName + }, + plugins: [ + { + name: 'externalize-deps', + setup(build) { + const options = { + root: path$o.dirname(fileName), + isBuild: true, + isProduction: true, + isRequire: !isESM, + preferRelative: false, + tryIndex: true, + mainFields: [], + browserField: false, + conditions: [], + overrideConditions: ['node'], + dedupe: [], + extensions: DEFAULT_EXTENSIONS$1, + preserveSymlinks: false + }; + // externalize bare imports + build.onResolve({ filter: /^[^.].*/ }, async ({ path: id, importer, kind }) => { + if (kind === 'entry-point' || + path$o.isAbsolute(id) || + isBuiltin(id)) { + return; + } + // partial deno support as `npm:` does not work with esbuild + if (id.startsWith('npm:')) { + return { external: true }; + } + let idFsPath = tryNodeResolve(id, importer, options, false)?.id; + if (idFsPath && (isESM || kind === 'dynamic-import')) { + idFsPath = pathToFileURL$1(idFsPath).href; + } + return { + path: idFsPath, + external: true + }; + }); + } + }, + { + name: 'inject-file-scope-variables', + setup(build) { + build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => { + const contents = await fs$l.promises.readFile(args.path, 'utf8'); + const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path$o.dirname(args.path))};` + + `const ${filenameVarName} = ${JSON.stringify(args.path)};` + + `const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL$1(args.path).href)};`; + return { + loader: args.path.endsWith('ts') ? 'ts' : 'js', + contents: injectValues + contents + }; + }); + } + } + ] + }); + const { text } = result.outputFiles[0]; + return { + code: text, + dependencies: result.metafile ? Object.keys(result.metafile.inputs) : [] + }; +} +const _require = createRequire$1(import.meta.url); +async function loadConfigFromBundledFile(fileName, bundledCode, isESM) { + // for esm, before we can register loaders without requiring users to run node + // with --experimental-loader themselves, we have to do a hack here: + // write it to disk, load it with native Node ESM, then delete the file. + if (isESM) { + const fileBase = `${fileName}.timestamp-${Date.now()}`; + const fileNameTmp = `${fileBase}.mjs`; + const fileUrl = `${pathToFileURL$1(fileBase)}.mjs`; + fs$l.writeFileSync(fileNameTmp, bundledCode); + try { + return (await dynamicImport(fileUrl)).default; + } + finally { + try { + fs$l.unlinkSync(fileNameTmp); + } + catch { + // already removed if this function is called twice simultaneously + } + } + } + // for cjs, we can register a custom loader via `_require.extensions` + else { + const extension = path$o.extname(fileName); + const realFileName = fs$l.realpathSync(fileName); + const loaderExt = extension in _require.extensions ? extension : '.js'; + const defaultLoader = _require.extensions[loaderExt]; + _require.extensions[loaderExt] = (module, filename) => { + if (filename === realFileName) { + module._compile(bundledCode, filename); + } + else { + defaultLoader(module, filename); + } + }; + // clear cache in case of server restart + delete _require.cache[_require.resolve(fileName)]; + const raw = _require(fileName); + _require.extensions[loaderExt] = defaultLoader; + return raw.__esModule ? raw.default : raw; + } +} +async function runConfigHook(config, plugins, configEnv) { + let conf = config; + for (const p of getSortedPluginsByHook('config', plugins)) { + const hook = p.config; + const handler = hook && 'handler' in hook ? hook.handler : hook; + if (handler) { + const res = await handler(conf, configEnv); + if (res) { + conf = mergeConfig(conf, res); + } + } + } + return conf; +} +function getDepOptimizationConfig(config, ssr) { + return ssr ? config.ssr.optimizeDeps : config.optimizeDeps; +} +function isDepsOptimizerEnabled(config, ssr) { + const { command } = config; + const { disabled } = getDepOptimizationConfig(config, ssr); + return !(disabled === true || + (command === 'build' && disabled === 'build') || + (command === 'serve' && disabled === 'dev')); +} + +export { commonjsGlobal as A, index$1 as B, build$1 as C, index as D, preview$1 as E, preprocessCSS as a, build as b, createServer as c, resolvePackageData as d, defineConfig as e, formatPostcssSourceMap as f, resolveConfig as g, resolveBaseUrl as h, getDepOptimizationConfig as i, isDepsOptimizerEnabled as j, mergeAlias as k, loadConfigFromFile as l, mergeConfig as m, normalizePath$3 as n, optimizeDeps as o, preview as p, createFilter as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, send$1 as u, createLogger as v, searchForWorkspaceRoot as w, loadEnv as x, resolveEnvPrefix as y, picocolors as z }; diff --git a/node_modules/vite/dist/node/chunks/dep-9deb2354.js b/node_modules/vite/dist/node/chunks/dep-9deb2354.js new file mode 100644 index 0000000..5fb2bbe --- /dev/null +++ b/node_modules/vite/dist/node/chunks/dep-9deb2354.js @@ -0,0 +1,877 @@ +import require$$0 from 'path'; +import resolve$2 from 'resolve'; +import require$$0__default from 'fs'; +import { l as lib } from './dep-07a79996.js'; + +import { fileURLToPath as __cjs_fileURLToPath } from 'node:url'; +import { dirname as __cjs_dirname } from 'node:path'; +import { createRequire as __cjs_createRequire } from 'node:module'; + +const __filename = __cjs_fileURLToPath(import.meta.url); +const __dirname = __cjs_dirname(__filename); +const require = __cjs_createRequire(import.meta.url); +const __require = require; +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + var e = m[i]; + if (typeof e !== 'string' && !Array.isArray(e)) { for (var k in e) { + if (k !== 'default' && !(k in n)) { + n[k] = e[k]; + } + } } + } + return n; +} + +var joinMedia$1 = function (parentMedia, childMedia) { + if (!parentMedia.length && childMedia.length) return childMedia + if (parentMedia.length && !childMedia.length) return parentMedia + if (!parentMedia.length && !childMedia.length) return [] + + const media = []; + + parentMedia.forEach(parentItem => { + childMedia.forEach(childItem => { + if (parentItem !== childItem) media.push(`${parentItem} and ${childItem}`); + }); + }); + + return media +}; + +var joinLayer$1 = function (parentLayer, childLayer) { + if (!parentLayer.length && childLayer.length) return childLayer + if (parentLayer.length && !childLayer.length) return parentLayer + if (!parentLayer.length && !childLayer.length) return [] + + return parentLayer.concat(childLayer) +}; + +// external tooling +const resolve$1 = resolve$2; + +const moduleDirectories = ["web_modules", "node_modules"]; + +function resolveModule(id, opts) { + return new Promise((res, rej) => { + resolve$1(id, opts, (err, path) => (err ? rej(err) : res(path))); + }) +} + +var resolveId$1 = function (id, base, options) { + const paths = options.path; + + const resolveOpts = { + basedir: base, + moduleDirectory: moduleDirectories.concat(options.addModulesDirectories), + paths, + extensions: [".css"], + packageFilter: function processPackage(pkg) { + if (pkg.style) pkg.main = pkg.style; + else if (!pkg.main || !/\.css$/.test(pkg.main)) pkg.main = "index.css"; + return pkg + }, + preserveSymlinks: false, + }; + + return resolveModule(`./${id}`, resolveOpts) + .catch(() => resolveModule(id, resolveOpts)) + .catch(() => { + if (paths.indexOf(base) === -1) paths.unshift(base); + + throw new Error( + `Failed to find '${id}' + in [ + ${paths.join(",\n ")} + ]` + ) + }) +}; + +var readCache$1 = {exports: {}}; + +var pify$2 = {exports: {}}; + +var processFn = function (fn, P, opts) { + return function () { + var that = this; + var args = new Array(arguments.length); + + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + return new P(function (resolve, reject) { + args.push(function (err, result) { + if (err) { + reject(err); + } else if (opts.multiArgs) { + var results = new Array(arguments.length - 1); + + for (var i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); + } + }); + + fn.apply(that, args); + }); + }; +}; + +var pify$1 = pify$2.exports = function (obj, P, opts) { + if (typeof P !== 'function') { + opts = P; + P = Promise; + } + + opts = opts || {}; + opts.exclude = opts.exclude || [/.+Sync$/]; + + var filter = function (key) { + var match = function (pattern) { + return typeof pattern === 'string' ? key === pattern : pattern.test(key); + }; + + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + var ret = typeof obj === 'function' ? function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, P, opts).apply(this, arguments); + } : {}; + + return Object.keys(obj).reduce(function (ret, key) { + var x = obj[key]; + + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x; + + return ret; + }, ret); +}; + +pify$1.all = pify$1; + +var fs = require$$0__default; +var path$2 = require$$0; +var pify = pify$2.exports; + +var stat = pify(fs.stat); +var readFile = pify(fs.readFile); +var resolve = path$2.resolve; + +var cache = Object.create(null); + +function convert(content, encoding) { + if (Buffer.isEncoding(encoding)) { + return content.toString(encoding); + } + return content; +} + +readCache$1.exports = function (path, encoding) { + path = resolve(path); + + return stat(path).then(function (stats) { + var item = cache[path]; + + if (item && item.mtime.getTime() === stats.mtime.getTime()) { + return convert(item.content, encoding); + } + + return readFile(path).then(function (data) { + cache[path] = { + mtime: stats.mtime, + content: data + }; + + return convert(data, encoding); + }); + }).catch(function (err) { + cache[path] = null; + return Promise.reject(err); + }); +}; + +readCache$1.exports.sync = function (path, encoding) { + path = resolve(path); + + try { + var stats = fs.statSync(path); + var item = cache[path]; + + if (item && item.mtime.getTime() === stats.mtime.getTime()) { + return convert(item.content, encoding); + } + + var data = fs.readFileSync(path); + + cache[path] = { + mtime: stats.mtime, + content: data + }; + + return convert(data, encoding); + } catch (err) { + cache[path] = null; + throw err; + } + +}; + +readCache$1.exports.get = function (path, encoding) { + path = resolve(path); + if (cache[path]) { + return convert(cache[path].content, encoding); + } + return null; +}; + +readCache$1.exports.clear = function () { + cache = Object.create(null); +}; + +const readCache = readCache$1.exports; + +var loadContent$1 = filename => readCache(filename, "utf-8"); + +// builtin tooling +const path$1 = require$$0; + +// placeholder tooling +let sugarss; + +var processContent$1 = function processContent( + result, + content, + filename, + options, + postcss +) { + const { plugins } = options; + const ext = path$1.extname(filename); + + const parserList = []; + + // SugarSS support: + if (ext === ".sss") { + if (!sugarss) { + try { + sugarss = __require('sugarss'); + } catch {} // Ignore + } + if (sugarss) + return runPostcss(postcss, content, filename, plugins, [sugarss]) + } + + // Syntax support: + if (result.opts.syntax?.parse) { + parserList.push(result.opts.syntax.parse); + } + + // Parser support: + if (result.opts.parser) parserList.push(result.opts.parser); + // Try the default as a last resort: + parserList.push(null); + + return runPostcss(postcss, content, filename, plugins, parserList) +}; + +function runPostcss(postcss, content, filename, plugins, parsers, index) { + if (!index) index = 0; + return postcss(plugins) + .process(content, { + from: filename, + parser: parsers[index], + }) + .catch(err => { + // If there's an error, try the next parser + index++; + // If there are no parsers left, throw it + if (index === parsers.length) throw err + return runPostcss(postcss, content, filename, plugins, parsers, index) + }) +} + +// external tooling +const valueParser = lib; + +// extended tooling +const { stringify } = valueParser; + +function split(params, start) { + const list = []; + const last = params.reduce((item, node, index) => { + if (index < start) return "" + if (node.type === "div" && node.value === ",") { + list.push(item); + return "" + } + return item + stringify(node) + }, ""); + list.push(last); + return list +} + +var parseStatements$1 = function (result, styles) { + const statements = []; + let nodes = []; + + styles.each(node => { + let stmt; + if (node.type === "atrule") { + if (node.name === "import") stmt = parseImport(result, node); + else if (node.name === "media") stmt = parseMedia(result, node); + else if (node.name === "charset") stmt = parseCharset(result, node); + } + + if (stmt) { + if (nodes.length) { + statements.push({ + type: "nodes", + nodes, + media: [], + layer: [], + }); + nodes = []; + } + statements.push(stmt); + } else nodes.push(node); + }); + + if (nodes.length) { + statements.push({ + type: "nodes", + nodes, + media: [], + layer: [], + }); + } + + return statements +}; + +function parseMedia(result, atRule) { + const params = valueParser(atRule.params).nodes; + return { + type: "media", + node: atRule, + media: split(params, 0), + layer: [], + } +} + +function parseCharset(result, atRule) { + if (atRule.prev()) { + return result.warn("@charset must precede all other statements", { + node: atRule, + }) + } + return { + type: "charset", + node: atRule, + media: [], + layer: [], + } +} + +function parseImport(result, atRule) { + let prev = atRule.prev(); + if (prev) { + do { + if ( + prev.type !== "comment" && + (prev.type !== "atrule" || + (prev.name !== "import" && + prev.name !== "charset" && + !(prev.name === "layer" && !prev.nodes))) + ) { + return result.warn( + "@import must precede all other statements (besides @charset or empty @layer)", + { node: atRule } + ) + } + prev = prev.prev(); + } while (prev) + } + + if (atRule.nodes) { + return result.warn( + "It looks like you didn't end your @import statement correctly. " + + "Child nodes are attached to it.", + { node: atRule } + ) + } + + const params = valueParser(atRule.params).nodes; + const stmt = { + type: "import", + node: atRule, + media: [], + layer: [], + }; + + // prettier-ignore + if ( + !params.length || + ( + params[0].type !== "string" || + !params[0].value + ) && + ( + params[0].type !== "function" || + params[0].value !== "url" || + !params[0].nodes.length || + !params[0].nodes[0].value + ) + ) { + return result.warn(`Unable to find uri in '${ atRule.toString() }'`, { + node: atRule, + }) + } + + if (params[0].type === "string") stmt.uri = params[0].value; + else stmt.uri = params[0].nodes[0].value; + stmt.fullUri = stringify(params[0]); + + let remainder = params; + if (remainder.length > 2) { + if ( + (remainder[2].type === "word" || remainder[2].type === "function") && + remainder[2].value === "layer" + ) { + if (remainder[1].type !== "space") { + return result.warn("Invalid import layer statement", { node: atRule }) + } + + if (remainder[2].nodes) { + stmt.layer = [stringify(remainder[2].nodes)]; + } else { + stmt.layer = [""]; + } + remainder = remainder.slice(2); + } + } + + if (remainder.length > 2) { + if (remainder[1].type !== "space") { + return result.warn("Invalid import media statement", { node: atRule }) + } + + stmt.media = split(remainder, 2); + } + + return stmt +} + +// builtin tooling +const path = require$$0; + +// internal tooling +const joinMedia = joinMedia$1; +const joinLayer = joinLayer$1; +const resolveId = resolveId$1; +const loadContent = loadContent$1; +const processContent = processContent$1; +const parseStatements = parseStatements$1; + +function AtImport(options) { + options = { + root: process.cwd(), + path: [], + skipDuplicates: true, + resolve: resolveId, + load: loadContent, + plugins: [], + addModulesDirectories: [], + nameLayer: null, + ...options, + }; + + options.root = path.resolve(options.root); + + // convert string to an array of a single element + if (typeof options.path === "string") options.path = [options.path]; + + if (!Array.isArray(options.path)) options.path = []; + + options.path = options.path.map(p => path.resolve(options.root, p)); + + return { + postcssPlugin: "postcss-import", + Once(styles, { result, atRule, postcss }) { + const state = { + importedFiles: {}, + hashFiles: {}, + rootFilename: null, + anonymousLayerCounter: 0, + }; + + if (styles.source?.input?.file) { + state.rootFilename = styles.source.input.file; + state.importedFiles[styles.source.input.file] = {}; + } + + if (options.plugins && !Array.isArray(options.plugins)) { + throw new Error("plugins option must be an array") + } + + if (options.nameLayer && typeof options.nameLayer !== "function") { + throw new Error("nameLayer option must be a function") + } + + return parseStyles(result, styles, options, state, [], []).then( + bundle => { + applyRaws(bundle); + applyMedia(bundle); + applyStyles(bundle, styles); + } + ) + + function applyRaws(bundle) { + bundle.forEach((stmt, index) => { + if (index === 0) return + + if (stmt.parent) { + const { before } = stmt.parent.node.raws; + if (stmt.type === "nodes") stmt.nodes[0].raws.before = before; + else stmt.node.raws.before = before; + } else if (stmt.type === "nodes") { + stmt.nodes[0].raws.before = stmt.nodes[0].raws.before || "\n"; + } + }); + } + + function applyMedia(bundle) { + bundle.forEach(stmt => { + if ( + (!stmt.media.length && !stmt.layer.length) || + stmt.type === "charset" + ) { + return + } + + if (stmt.type === "import") { + stmt.node.params = `${stmt.fullUri} ${stmt.media.join(", ")}`; + } else if (stmt.type === "media") { + if (stmt.layer.length) { + const layerNode = atRule({ + name: "layer", + params: stmt.layer.filter(layer => layer !== "").join("."), + source: stmt.node.source, + }); + + if (stmt.parentMedia?.length) { + const mediaNode = atRule({ + name: "media", + params: stmt.parentMedia.join(", "), + source: stmt.node.source, + }); + + mediaNode.append(layerNode); + layerNode.append(stmt.node); + stmt.node = mediaNode; + } else { + layerNode.append(stmt.node); + stmt.node = layerNode; + } + } else { + stmt.node.params = stmt.media.join(", "); + } + } else { + const { nodes } = stmt; + const { parent } = nodes[0]; + + let outerAtRule; + let innerAtRule; + if (stmt.media.length && stmt.layer.length) { + const mediaNode = atRule({ + name: "media", + params: stmt.media.join(", "), + source: parent.source, + }); + + const layerNode = atRule({ + name: "layer", + params: stmt.layer.filter(layer => layer !== "").join("."), + source: parent.source, + }); + + mediaNode.append(layerNode); + innerAtRule = layerNode; + outerAtRule = mediaNode; + } else if (stmt.media.length) { + const mediaNode = atRule({ + name: "media", + params: stmt.media.join(", "), + source: parent.source, + }); + + innerAtRule = mediaNode; + outerAtRule = mediaNode; + } else if (stmt.layer.length) { + const layerNode = atRule({ + name: "layer", + params: stmt.layer.filter(layer => layer !== "").join("."), + source: parent.source, + }); + + innerAtRule = layerNode; + outerAtRule = layerNode; + } + + parent.insertBefore(nodes[0], outerAtRule); + + // remove nodes + nodes.forEach(node => { + node.parent = undefined; + }); + + // better output + nodes[0].raws.before = nodes[0].raws.before || "\n"; + + // wrap new rules with media query and/or layer at rule + innerAtRule.append(nodes); + + stmt.type = "media"; + stmt.node = outerAtRule; + delete stmt.nodes; + } + }); + } + + function applyStyles(bundle, styles) { + styles.nodes = []; + + // Strip additional statements. + bundle.forEach(stmt => { + if (["charset", "import", "media"].includes(stmt.type)) { + stmt.node.parent = undefined; + styles.append(stmt.node); + } else if (stmt.type === "nodes") { + stmt.nodes.forEach(node => { + node.parent = undefined; + styles.append(node); + }); + } + }); + } + + function parseStyles(result, styles, options, state, media, layer) { + const statements = parseStatements(result, styles); + + return Promise.resolve(statements) + .then(stmts => { + // process each statement in series + return stmts.reduce((promise, stmt) => { + return promise.then(() => { + stmt.media = joinMedia(media, stmt.media || []); + stmt.parentMedia = media; + stmt.layer = joinLayer(layer, stmt.layer || []); + + // skip protocol base uri (protocol://url) or protocol-relative + if ( + stmt.type !== "import" || + /^(?:[a-z]+:)?\/\//i.test(stmt.uri) + ) { + return + } + + if (options.filter && !options.filter(stmt.uri)) { + // rejected by filter + return + } + + return resolveImportId(result, stmt, options, state) + }) + }, Promise.resolve()) + }) + .then(() => { + let charset; + const imports = []; + const bundle = []; + + function handleCharset(stmt) { + if (!charset) charset = stmt; + // charsets aren't case-sensitive, so convert to lower case to compare + else if ( + stmt.node.params.toLowerCase() !== + charset.node.params.toLowerCase() + ) { + throw new Error( + `Incompatable @charset statements: + ${stmt.node.params} specified in ${stmt.node.source.input.file} + ${charset.node.params} specified in ${charset.node.source.input.file}` + ) + } + } + + // squash statements and their children + statements.forEach(stmt => { + if (stmt.type === "charset") handleCharset(stmt); + else if (stmt.type === "import") { + if (stmt.children) { + stmt.children.forEach((child, index) => { + if (child.type === "import") imports.push(child); + else if (child.type === "charset") handleCharset(child); + else bundle.push(child); + // For better output + if (index === 0) child.parent = stmt; + }); + } else imports.push(stmt); + } else if (stmt.type === "media" || stmt.type === "nodes") { + bundle.push(stmt); + } + }); + + return charset + ? [charset, ...imports.concat(bundle)] + : imports.concat(bundle) + }) + } + + function resolveImportId(result, stmt, options, state) { + const atRule = stmt.node; + let sourceFile; + if (atRule.source?.input?.file) { + sourceFile = atRule.source.input.file; + } + const base = sourceFile + ? path.dirname(atRule.source.input.file) + : options.root; + + return Promise.resolve(options.resolve(stmt.uri, base, options)) + .then(paths => { + if (!Array.isArray(paths)) paths = [paths]; + // Ensure that each path is absolute: + return Promise.all( + paths.map(file => { + return !path.isAbsolute(file) + ? resolveId(file, base, options) + : file + }) + ) + }) + .then(resolved => { + // Add dependency messages: + resolved.forEach(file => { + result.messages.push({ + type: "dependency", + plugin: "postcss-import", + file, + parent: sourceFile, + }); + }); + + return Promise.all( + resolved.map(file => { + return loadImportContent(result, stmt, file, options, state) + }) + ) + }) + .then(result => { + // Merge loaded statements + stmt.children = result.reduce((result, statements) => { + return statements ? result.concat(statements) : result + }, []); + }) + } + + function loadImportContent(result, stmt, filename, options, state) { + const atRule = stmt.node; + const { media, layer } = stmt; + layer.forEach((layerPart, i) => { + if (layerPart === "") { + if (options.nameLayer) { + layer[i] = options + .nameLayer(state.anonymousLayerCounter++, state.rootFilename) + .toString(); + } else { + throw atRule.error( + `When using anonymous layers in @import you must also set the "nameLayer" plugin option` + ) + } + } + }); + + if (options.skipDuplicates) { + // skip files already imported at the same scope + if (state.importedFiles[filename]?.[media]?.[layer]) { + return + } + + // save imported files to skip them next time + if (!state.importedFiles[filename]) { + state.importedFiles[filename] = {}; + } + if (!state.importedFiles[filename][media]) { + state.importedFiles[filename][media] = {}; + } + state.importedFiles[filename][media][layer] = true; + } + + return Promise.resolve(options.load(filename, options)).then( + content => { + if (content.trim() === "") { + result.warn(`${filename} is empty`, { node: atRule }); + return + } + + // skip previous imported files not containing @import rules + if (state.hashFiles[content]?.[media]?.[layer]) { + return + } + + return processContent( + result, + content, + filename, + options, + postcss + ).then(importedResult => { + const styles = importedResult.root; + result.messages = result.messages.concat(importedResult.messages); + + if (options.skipDuplicates) { + const hasImport = styles.some(child => { + return child.type === "atrule" && child.name === "import" + }); + if (!hasImport) { + // save hash files to skip them next time + if (!state.hashFiles[content]) { + state.hashFiles[content] = {}; + } + if (!state.hashFiles[content][media]) { + state.hashFiles[content][media] = {}; + } + state.hashFiles[content][media][layer] = true; + } + } + + // recursion: import @import from imported file + return parseStyles(result, styles, options, state, media, layer) + }) + } + ) + } + }, + } +} + +AtImport.postcss = true; + +var postcssImport = AtImport; + +var index = /*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': postcssImport +}, [postcssImport]); + +export { index as i }; diff --git a/node_modules/vite/dist/node/cli.js b/node_modules/vite/dist/node/cli.js new file mode 100644 index 0000000..b5356ed --- /dev/null +++ b/node_modules/vite/dist/node/cli.js @@ -0,0 +1,831 @@ +import { performance } from 'node:perf_hooks'; +import { EventEmitter } from 'events'; +import { z as picocolors, v as createLogger, g as resolveConfig } from './chunks/dep-5605cfa4.js'; +import { VERSION } from './constants.js'; +import 'node:fs'; +import 'node:path'; +import 'node:url'; +import 'node:module'; +import 'tty'; +import 'esbuild'; +import 'path'; +import 'fs'; +import 'assert'; +import 'util'; +import 'net'; +import 'url'; +import 'http'; +import 'stream'; +import 'os'; +import 'child_process'; +import 'node:os'; +import 'node:crypto'; +import 'node:util'; +import 'node:dns'; +import 'resolve'; +import 'crypto'; +import 'node:buffer'; +import 'module'; +import 'worker_threads'; +import 'zlib'; +import 'https'; +import 'tls'; +import 'node:http'; +import 'node:https'; +import 'querystring'; +import 'node:readline'; +import 'node:child_process'; +import 'node:zlib'; + +function toArr(any) { + return any == null ? [] : Array.isArray(any) ? any : [any]; +} + +function toVal(out, key, val, opts) { + var x, old=out[key], nxt=( + !!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val)) + : typeof val === 'boolean' ? val + : !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val)) + : (x = +val,x * 0 === 0) ? x : val + ); + out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]); +} + +function mri2 (args, opts) { + args = args || []; + opts = opts || {}; + + var k, arr, arg, name, val, out={ _:[] }; + var i=0, j=0, idx=0, len=args.length; + + const alibi = opts.alias !== void 0; + const strict = opts.unknown !== void 0; + const defaults = opts.default !== void 0; + + opts.alias = opts.alias || {}; + opts.string = toArr(opts.string); + opts.boolean = toArr(opts.boolean); + + if (alibi) { + for (k in opts.alias) { + arr = opts.alias[k] = toArr(opts.alias[k]); + for (i=0; i < arr.length; i++) { + (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1); + } + } + } + + for (i=opts.boolean.length; i-- > 0;) { + arr = opts.alias[opts.boolean[i]] || []; + for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]); + } + + for (i=opts.string.length; i-- > 0;) { + arr = opts.alias[opts.string[i]] || []; + for (j=arr.length; j-- > 0;) opts.string.push(arr[j]); + } + + if (defaults) { + for (k in opts.default) { + name = typeof opts.default[k]; + arr = opts.alias[k] = opts.alias[k] || []; + if (opts[name] !== void 0) { + opts[name].push(k); + for (i=0; i < arr.length; i++) { + opts[name].push(arr[i]); + } + } + } + } + + const keys = strict ? Object.keys(opts.alias) : []; + + for (i=0; i < len; i++) { + arg = args[i]; + + if (arg === '--') { + out._ = out._.concat(args.slice(++i)); + break; + } + + for (j=0; j < arg.length; j++) { + if (arg.charCodeAt(j) !== 45) break; // "-" + } + + if (j === 0) { + out._.push(arg); + } else if (arg.substring(j, j + 3) === 'no-') { + name = arg.substring(j + 3); + if (strict && !~keys.indexOf(name)) { + return opts.unknown(arg); + } + out[name] = false; + } else { + for (idx=j+1; idx < arg.length; idx++) { + if (arg.charCodeAt(idx) === 61) break; // "=" + } + + name = arg.substring(j, idx); + val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]); + arr = (j === 2 ? [name] : name); + + for (idx=0; idx < arr.length; idx++) { + name = arr[idx]; + if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name); + toVal(out, name, (idx + 1 < arr.length) || val, opts); + } + } + } + + if (defaults) { + for (k in opts.default) { + if (out[k] === void 0) { + out[k] = opts.default[k]; + } + } + } + + if (alibi) { + for (k in out) { + arr = opts.alias[k] || []; + while (arr.length > 0) { + out[arr.shift()] = out[k]; + } + } + } + + return out; +} + +const removeBrackets = (v) => v.replace(/[<[].+/, "").trim(); +const findAllBrackets = (v) => { + const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g; + const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g; + const res = []; + const parse = (match) => { + let variadic = false; + let value = match[1]; + if (value.startsWith("...")) { + value = value.slice(3); + variadic = true; + } + return { + required: match[0].startsWith("<"), + value, + variadic + }; + }; + let angledMatch; + while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) { + res.push(parse(angledMatch)); + } + let squareMatch; + while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) { + res.push(parse(squareMatch)); + } + return res; +}; +const getMriOptions = (options) => { + const result = {alias: {}, boolean: []}; + for (const [index, option] of options.entries()) { + if (option.names.length > 1) { + result.alias[option.names[0]] = option.names.slice(1); + } + if (option.isBoolean) { + if (option.negated) { + const hasStringTypeOption = options.some((o, i) => { + return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean"; + }); + if (!hasStringTypeOption) { + result.boolean.push(option.names[0]); + } + } else { + result.boolean.push(option.names[0]); + } + } + } + return result; +}; +const findLongest = (arr) => { + return arr.sort((a, b) => { + return a.length > b.length ? -1 : 1; + })[0]; +}; +const padRight = (str, length) => { + return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`; +}; +const camelcase = (input) => { + return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => { + return p1 + p2.toUpperCase(); + }); +}; +const setDotProp = (obj, keys, val) => { + let i = 0; + let length = keys.length; + let t = obj; + let x; + for (; i < length; ++i) { + x = t[keys[i]]; + t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : []; + } +}; +const setByType = (obj, transforms) => { + for (const key of Object.keys(transforms)) { + const transform = transforms[key]; + if (transform.shouldTransform) { + obj[key] = Array.prototype.concat.call([], obj[key]); + if (typeof transform.transformFunction === "function") { + obj[key] = obj[key].map(transform.transformFunction); + } + } + } +}; +const getFileName = (input) => { + const m = /([^\\\/]+)$/.exec(input); + return m ? m[1] : ""; +}; +const camelcaseOptionName = (name) => { + return name.split(".").map((v, i) => { + return i === 0 ? camelcase(v) : v; + }).join("."); +}; +class CACError extends Error { + constructor(message) { + super(message); + this.name = this.constructor.name; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error(message).stack; + } + } +} + +class Option { + constructor(rawName, description, config) { + this.rawName = rawName; + this.description = description; + this.config = Object.assign({}, config); + rawName = rawName.replace(/\.\*/g, ""); + this.negated = false; + this.names = removeBrackets(rawName).split(",").map((v) => { + let name = v.trim().replace(/^-{1,2}/, ""); + if (name.startsWith("no-")) { + this.negated = true; + name = name.replace(/^no-/, ""); + } + return camelcaseOptionName(name); + }).sort((a, b) => a.length > b.length ? 1 : -1); + this.name = this.names[this.names.length - 1]; + if (this.negated && this.config.default == null) { + this.config.default = true; + } + if (rawName.includes("<")) { + this.required = true; + } else if (rawName.includes("[")) { + this.required = false; + } else { + this.isBoolean = true; + } + } +} + +const processArgs = process.argv; +const platformInfo = `${process.platform}-${process.arch} node-${process.version}`; + +class Command { + constructor(rawName, description, config = {}, cli) { + this.rawName = rawName; + this.description = description; + this.config = config; + this.cli = cli; + this.options = []; + this.aliasNames = []; + this.name = removeBrackets(rawName); + this.args = findAllBrackets(rawName); + this.examples = []; + } + usage(text) { + this.usageText = text; + return this; + } + allowUnknownOptions() { + this.config.allowUnknownOptions = true; + return this; + } + ignoreOptionDefaultValue() { + this.config.ignoreOptionDefaultValue = true; + return this; + } + version(version, customFlags = "-v, --version") { + this.versionNumber = version; + this.option(customFlags, "Display version number"); + return this; + } + example(example) { + this.examples.push(example); + return this; + } + option(rawName, description, config) { + const option = new Option(rawName, description, config); + this.options.push(option); + return this; + } + alias(name) { + this.aliasNames.push(name); + return this; + } + action(callback) { + this.commandAction = callback; + return this; + } + isMatched(name) { + return this.name === name || this.aliasNames.includes(name); + } + get isDefaultCommand() { + return this.name === "" || this.aliasNames.includes("!"); + } + get isGlobalCommand() { + return this instanceof GlobalCommand; + } + hasOption(name) { + name = name.split(".")[0]; + return this.options.find((option) => { + return option.names.includes(name); + }); + } + outputHelp() { + const {name, commands} = this.cli; + const { + versionNumber, + options: globalOptions, + helpCallback + } = this.cli.globalCommand; + let sections = [ + { + body: `${name}${versionNumber ? `/${versionNumber}` : ""}` + } + ]; + sections.push({ + title: "Usage", + body: ` $ ${name} ${this.usageText || this.rawName}` + }); + const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0; + if (showCommands) { + const longestCommandName = findLongest(commands.map((command) => command.rawName)); + sections.push({ + title: "Commands", + body: commands.map((command) => { + return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`; + }).join("\n") + }); + sections.push({ + title: `For more info, run any command with the \`--help\` flag`, + body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n") + }); + } + let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []]; + if (!this.isGlobalCommand && !this.isDefaultCommand) { + options = options.filter((option) => option.name !== "version"); + } + if (options.length > 0) { + const longestOptionName = findLongest(options.map((option) => option.rawName)); + sections.push({ + title: "Options", + body: options.map((option) => { + return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`; + }).join("\n") + }); + } + if (this.examples.length > 0) { + sections.push({ + title: "Examples", + body: this.examples.map((example) => { + if (typeof example === "function") { + return example(name); + } + return example; + }).join("\n") + }); + } + if (helpCallback) { + sections = helpCallback(sections) || sections; + } + console.log(sections.map((section) => { + return section.title ? `${section.title}: +${section.body}` : section.body; + }).join("\n\n")); + } + outputVersion() { + const {name} = this.cli; + const {versionNumber} = this.cli.globalCommand; + if (versionNumber) { + console.log(`${name}/${versionNumber} ${platformInfo}`); + } + } + checkRequiredArgs() { + const minimalArgsCount = this.args.filter((arg) => arg.required).length; + if (this.cli.args.length < minimalArgsCount) { + throw new CACError(`missing required args for command \`${this.rawName}\``); + } + } + checkUnknownOptions() { + const {options, globalCommand} = this.cli; + if (!this.config.allowUnknownOptions) { + for (const name of Object.keys(options)) { + if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) { + throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``); + } + } + } + } + checkOptionValue() { + const {options: parsedOptions, globalCommand} = this.cli; + const options = [...globalCommand.options, ...this.options]; + for (const option of options) { + const value = parsedOptions[option.name.split(".")[0]]; + if (option.required) { + const hasNegated = options.some((o) => o.negated && o.names.includes(option.name)); + if (value === true || value === false && !hasNegated) { + throw new CACError(`option \`${option.rawName}\` value is missing`); + } + } + } + } +} +class GlobalCommand extends Command { + constructor(cli) { + super("@@global@@", "", {}, cli); + } +} + +var __assign = Object.assign; +class CAC extends EventEmitter { + constructor(name = "") { + super(); + this.name = name; + this.commands = []; + this.rawArgs = []; + this.args = []; + this.options = {}; + this.globalCommand = new GlobalCommand(this); + this.globalCommand.usage(" [options]"); + } + usage(text) { + this.globalCommand.usage(text); + return this; + } + command(rawName, description, config) { + const command = new Command(rawName, description || "", config, this); + command.globalCommand = this.globalCommand; + this.commands.push(command); + return command; + } + option(rawName, description, config) { + this.globalCommand.option(rawName, description, config); + return this; + } + help(callback) { + this.globalCommand.option("-h, --help", "Display this message"); + this.globalCommand.helpCallback = callback; + this.showHelpOnExit = true; + return this; + } + version(version, customFlags = "-v, --version") { + this.globalCommand.version(version, customFlags); + this.showVersionOnExit = true; + return this; + } + example(example) { + this.globalCommand.example(example); + return this; + } + outputHelp() { + if (this.matchedCommand) { + this.matchedCommand.outputHelp(); + } else { + this.globalCommand.outputHelp(); + } + } + outputVersion() { + this.globalCommand.outputVersion(); + } + setParsedInfo({args, options}, matchedCommand, matchedCommandName) { + this.args = args; + this.options = options; + if (matchedCommand) { + this.matchedCommand = matchedCommand; + } + if (matchedCommandName) { + this.matchedCommandName = matchedCommandName; + } + return this; + } + unsetMatchedCommand() { + this.matchedCommand = void 0; + this.matchedCommandName = void 0; + } + parse(argv = processArgs, { + run = true + } = {}) { + this.rawArgs = argv; + if (!this.name) { + this.name = argv[1] ? getFileName(argv[1]) : "cli"; + } + let shouldParse = true; + for (const command of this.commands) { + const parsed = this.mri(argv.slice(2), command); + const commandName = parsed.args[0]; + if (command.isMatched(commandName)) { + shouldParse = false; + const parsedInfo = __assign(__assign({}, parsed), { + args: parsed.args.slice(1) + }); + this.setParsedInfo(parsedInfo, command, commandName); + this.emit(`command:${commandName}`, command); + } + } + if (shouldParse) { + for (const command of this.commands) { + if (command.name === "") { + shouldParse = false; + const parsed = this.mri(argv.slice(2), command); + this.setParsedInfo(parsed, command); + this.emit(`command:!`, command); + } + } + } + if (shouldParse) { + const parsed = this.mri(argv.slice(2)); + this.setParsedInfo(parsed); + } + if (this.options.help && this.showHelpOnExit) { + this.outputHelp(); + run = false; + this.unsetMatchedCommand(); + } + if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) { + this.outputVersion(); + run = false; + this.unsetMatchedCommand(); + } + const parsedArgv = {args: this.args, options: this.options}; + if (run) { + this.runMatchedCommand(); + } + if (!this.matchedCommand && this.args[0]) { + this.emit("command:*"); + } + return parsedArgv; + } + mri(argv, command) { + const cliOptions = [ + ...this.globalCommand.options, + ...command ? command.options : [] + ]; + const mriOptions = getMriOptions(cliOptions); + let argsAfterDoubleDashes = []; + const doubleDashesIndex = argv.indexOf("--"); + if (doubleDashesIndex > -1) { + argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1); + argv = argv.slice(0, doubleDashesIndex); + } + let parsed = mri2(argv, mriOptions); + parsed = Object.keys(parsed).reduce((res, name) => { + return __assign(__assign({}, res), { + [camelcaseOptionName(name)]: parsed[name] + }); + }, {_: []}); + const args = parsed._; + const options = { + "--": argsAfterDoubleDashes + }; + const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue; + let transforms = Object.create(null); + for (const cliOption of cliOptions) { + if (!ignoreDefault && cliOption.config.default !== void 0) { + for (const name of cliOption.names) { + options[name] = cliOption.config.default; + } + } + if (Array.isArray(cliOption.config.type)) { + if (transforms[cliOption.name] === void 0) { + transforms[cliOption.name] = Object.create(null); + transforms[cliOption.name]["shouldTransform"] = true; + transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0]; + } + } + } + for (const key of Object.keys(parsed)) { + if (key !== "_") { + const keys = key.split("."); + setDotProp(options, keys, parsed[key]); + setByType(options, transforms); + } + } + return { + args, + options + }; + } + runMatchedCommand() { + const {args, options, matchedCommand: command} = this; + if (!command || !command.commandAction) + return; + command.checkUnknownOptions(); + command.checkOptionValue(); + command.checkRequiredArgs(); + const actionArgs = []; + command.args.forEach((arg, index) => { + if (arg.variadic) { + actionArgs.push(args.slice(index)); + } else { + actionArgs.push(args[index]); + } + }); + actionArgs.push(options); + return command.commandAction.apply(this, actionArgs); + } +} + +const cac = (name = "") => new CAC(name); + +const cli = cac('vite'); +const filterDuplicateOptions = (options) => { + for (const [key, value] of Object.entries(options)) { + if (Array.isArray(value)) { + options[key] = value[value.length - 1]; + } + } +}; +/** + * removing global flags before passing as command specific sub-configs + */ +function cleanOptions(options) { + const ret = { ...options }; + delete ret['--']; + delete ret.c; + delete ret.config; + delete ret.base; + delete ret.l; + delete ret.logLevel; + delete ret.clearScreen; + delete ret.d; + delete ret.debug; + delete ret.f; + delete ret.filter; + delete ret.m; + delete ret.mode; + return ret; +} +cli + .option('-c, --config ', `[string] use specified config file`) + .option('--base ', `[string] public base path (default: /)`) + .option('-l, --logLevel ', `[string] info | warn | error | silent`) + .option('--clearScreen', `[boolean] allow/disable clear screen when logging`) + .option('-d, --debug [feat]', `[string | boolean] show debug logs`) + .option('-f, --filter ', `[string] filter debug logs`) + .option('-m, --mode ', `[string] set env mode`); +// dev +cli + .command('[root]', 'start dev server') // default command + .alias('serve') // the command is called 'serve' in Vite's API + .alias('dev') // alias to align with the script name + .option('--host [host]', `[string] specify hostname`) + .option('--port ', `[number] specify port`) + .option('--https', `[boolean] use TLS + HTTP/2`) + .option('--open [path]', `[boolean | string] open browser on startup`) + .option('--cors', `[boolean] enable CORS`) + .option('--strictPort', `[boolean] exit if specified port is already in use`) + .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`) + .action(async (root, options) => { + filterDuplicateOptions(options); + // output structure is preserved even after bundling so require() + // is ok here + const { createServer } = await import('./chunks/dep-5605cfa4.js').then(function (n) { return n.D; }); + try { + const server = await createServer({ + root, + base: options.base, + mode: options.mode, + configFile: options.config, + logLevel: options.logLevel, + clearScreen: options.clearScreen, + optimizeDeps: { force: options.force }, + server: cleanOptions(options) + }); + if (!server.httpServer) { + throw new Error('HTTP server not available'); + } + await server.listen(); + const info = server.config.logger.info; + // @ts-ignore + const viteStartTime = global.__vite_start_time ?? false; + const startupDurationString = viteStartTime + ? picocolors.exports.dim(`ready in ${picocolors.exports.reset(picocolors.exports.bold(Math.ceil(performance.now() - viteStartTime)))} ms`) + : ''; + info(`\n ${picocolors.exports.green(`${picocolors.exports.bold('VITE')} v${VERSION}`)} ${startupDurationString}\n`, { clear: !server.config.logger.hasWarned }); + server.printUrls(); + } + catch (e) { + createLogger(options.logLevel).error(picocolors.exports.red(`error when starting dev server:\n${e.stack}`), { error: e }); + process.exit(1); + } +}); +// build +cli + .command('build [root]', 'build for production') + .option('--target ', `[string] transpile target (default: 'modules')`) + .option('--outDir ', `[string] output directory (default: dist)`) + .option('--assetsDir ', `[string] directory under outDir to place assets in (default: assets)`) + .option('--assetsInlineLimit ', `[number] static asset base64 inline threshold in bytes (default: 4096)`) + .option('--ssr [entry]', `[string] build specified entry for server-side rendering`) + .option('--sourcemap', `[boolean] output source maps for build (default: false)`) + .option('--minify [minifier]', `[boolean | "terser" | "esbuild"] enable/disable minification, ` + + `or specify minifier to use (default: esbuild)`) + .option('--manifest [name]', `[boolean | string] emit build manifest json`) + .option('--ssrManifest [name]', `[boolean | string] emit ssr manifest json`) + .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle (experimental)`) + .option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`) + .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`) + .action(async (root, options) => { + filterDuplicateOptions(options); + const { build } = await import('./chunks/dep-5605cfa4.js').then(function (n) { return n.C; }); + const buildOptions = cleanOptions(options); + try { + await build({ + root, + base: options.base, + mode: options.mode, + configFile: options.config, + logLevel: options.logLevel, + clearScreen: options.clearScreen, + optimizeDeps: { force: options.force }, + build: buildOptions + }); + } + catch (e) { + createLogger(options.logLevel).error(picocolors.exports.red(`error during build:\n${e.stack}`), { error: e }); + process.exit(1); + } +}); +// optimize +cli + .command('optimize [root]', 'pre-bundle dependencies') + .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`) + .action(async (root, options) => { + filterDuplicateOptions(options); + const { optimizeDeps } = await import('./chunks/dep-5605cfa4.js').then(function (n) { return n.B; }); + try { + const config = await resolveConfig({ + root, + base: options.base, + configFile: options.config, + logLevel: options.logLevel + }, 'build', 'development'); + await optimizeDeps(config, options.force, true); + } + catch (e) { + createLogger(options.logLevel).error(picocolors.exports.red(`error when optimizing deps:\n${e.stack}`), { error: e }); + process.exit(1); + } +}); +cli + .command('preview [root]', 'locally preview production build') + .option('--host [host]', `[string] specify hostname`) + .option('--port ', `[number] specify port`) + .option('--strictPort', `[boolean] exit if specified port is already in use`) + .option('--https', `[boolean] use TLS + HTTP/2`) + .option('--open [path]', `[boolean | string] open browser on startup`) + .option('--outDir ', `[string] output directory (default: dist)`) + .action(async (root, options) => { + filterDuplicateOptions(options); + const { preview } = await import('./chunks/dep-5605cfa4.js').then(function (n) { return n.E; }); + try { + const server = await preview({ + root, + base: options.base, + configFile: options.config, + logLevel: options.logLevel, + mode: options.mode, + build: { + outDir: options.outDir + }, + preview: { + port: options.port, + strictPort: options.strictPort, + host: options.host, + https: options.https, + open: options.open + } + }); + server.printUrls(); + } + catch (e) { + createLogger(options.logLevel).error(picocolors.exports.red(`error when starting preview server:\n${e.stack}`), { error: e }); + process.exit(1); + } +}); +cli.help(); +cli.version(VERSION); +cli.parse(); diff --git a/node_modules/vite/dist/node/constants.js b/node_modules/vite/dist/node/constants.js new file mode 100644 index 0000000..8491175 --- /dev/null +++ b/node_modules/vite/dist/node/constants.js @@ -0,0 +1,120 @@ +import path, { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +var version = "3.2.5"; + +const VERSION = version; +const DEFAULT_MAIN_FIELDS = [ + 'module', + 'jsnext:main', + 'jsnext' +]; +// Baseline support browserslist +// "defaults and supports es6-module and supports es6-module-dynamic-import" +// Higher browser versions may be needed for extra features. +const ESBUILD_MODULES_TARGET = [ + 'es2020', + 'edge88', + 'firefox78', + 'chrome87', + 'safari13' // transpile nullish coalescing +]; +const DEFAULT_EXTENSIONS = [ + '.mjs', + '.js', + '.mts', + '.ts', + '.jsx', + '.tsx', + '.json' +]; +const DEFAULT_CONFIG_FILES = [ + 'vite.config.js', + 'vite.config.mjs', + 'vite.config.ts', + 'vite.config.cjs', + 'vite.config.mts', + 'vite.config.cts' +]; +const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/; +const OPTIMIZABLE_ENTRY_RE = /\.(?:[cm]?[jt]s)$/; +const SPECIAL_QUERY_RE = /[\?&](?:worker|sharedworker|raw|url)\b/; +/** + * Prefix for resolved fs paths, since windows paths may not be valid as URLs. + */ +const FS_PREFIX = `/@fs/`; +/** + * Prefix for resolved Ids that are not valid browser import specifiers + */ +const VALID_ID_PREFIX = `/@id/`; +/** + * Plugins that use 'virtual modules' (e.g. for helper functions), prefix the + * module ID with `\0`, a convention from the rollup ecosystem. + * This prevents other plugins from trying to process the id (like node resolution), + * and core features like sourcemaps can use this info to differentiate between + * virtual modules and regular files. + * `\0` is not a permitted char in import URLs so we have to replace them during + * import analysis. The id will be decoded back before entering the plugins pipeline. + * These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual + * modules in the browser end up encoded as `/@id/__x00__{id}` + */ +const NULL_BYTE_PLACEHOLDER = `__x00__`; +const CLIENT_PUBLIC_PATH = `/@vite/client`; +const ENV_PUBLIC_PATH = `/@vite/env`; +const VITE_PACKAGE_DIR = resolve( +// import.meta.url is `dist/node/constants.js` after bundle +fileURLToPath(import.meta.url), '../../..'); +const CLIENT_ENTRY = resolve(VITE_PACKAGE_DIR, 'dist/client/client.mjs'); +const ENV_ENTRY = resolve(VITE_PACKAGE_DIR, 'dist/client/env.mjs'); +const CLIENT_DIR = path.dirname(CLIENT_ENTRY); +// ** READ THIS ** before editing `KNOWN_ASSET_TYPES`. +// If you add an asset to `KNOWN_ASSET_TYPES`, make sure to also add it +// to the TypeScript declaration file `packages/vite/client.d.ts` and +// add a mime type to the `registerCustomMime` in +// `packages/vite/src/node/plugin/assets.ts` if mime type cannot be +// looked up by mrmime. +const KNOWN_ASSET_TYPES = [ + // images + 'png', + 'jpe?g', + 'jfif', + 'pjpeg', + 'pjp', + 'gif', + 'svg', + 'ico', + 'webp', + 'avif', + // media + 'mp4', + 'webm', + 'ogg', + 'mp3', + 'wav', + 'flac', + 'aac', + // fonts + 'woff2?', + 'eot', + 'ttf', + 'otf', + // other + 'webmanifest', + 'pdf', + 'txt' +]; +const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`); +const DEP_VERSION_RE = /[\?&](v=[\w\.-]+)\b/; +const loopbackHosts = new Set([ + 'localhost', + '127.0.0.1', + '::1', + '0000:0000:0000:0000:0000:0000:0000:0001' +]); +const wildcardHosts = new Set([ + '0.0.0.0', + '::', + '0000:0000:0000:0000:0000:0000:0000:0000' +]); + +export { CLIENT_DIR, CLIENT_ENTRY, CLIENT_PUBLIC_PATH, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES, DEFAULT_EXTENSIONS, DEFAULT_MAIN_FIELDS, DEP_VERSION_RE, ENV_ENTRY, ENV_PUBLIC_PATH, ESBUILD_MODULES_TARGET, FS_PREFIX, JS_TYPES_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, OPTIMIZABLE_ENTRY_RE, SPECIAL_QUERY_RE, VALID_ID_PREFIX, VERSION, VITE_PACKAGE_DIR, loopbackHosts, wildcardHosts }; diff --git a/node_modules/vite/dist/node/index.d.ts b/node_modules/vite/dist/node/index.d.ts new file mode 100644 index 0000000..d35b7fe --- /dev/null +++ b/node_modules/vite/dist/node/index.d.ts @@ -0,0 +1,3248 @@ +/// + +import type { Agent } from 'node:http'; +import type { BuildOptions as BuildOptions_2 } from 'esbuild'; +import type { ClientRequest } from 'node:http'; +import type { ClientRequestArgs } from 'node:http'; +import { ConnectedPayload } from "../../types/hmrPayload"; +import { CustomEventMap } from "../../types/customEvent"; +import { CustomPayload } from "../../types/hmrPayload"; +import type { CustomPluginOptions } from 'rollup'; +import type { Duplex } from 'node:stream'; +import type { DuplexOptions } from 'node:stream'; +import { ErrorPayload } from "../../types/hmrPayload"; +import { TransformOptions as EsbuildTransformOptions } from 'esbuild'; +import { version as esbuildVersion } from 'esbuild'; +import { EventEmitter } from 'node:events'; +import * as events from 'node:events'; +import type { ExistingRawSourceMap } from 'rollup'; +import type * as fs from 'node:fs'; +import { FullReloadPayload } from "../../types/hmrPayload"; +import { GeneralImportGlobOptions } from "../../types/importGlob"; +import type { GetManualChunk } from 'rollup'; +import { HMRPayload } from "../../types/hmrPayload"; +import * as http from 'node:http'; +import { ImportGlobEagerFunction } from "../../types/importGlob"; +import { ImportGlobFunction } from "../../types/importGlob"; +import { ImportGlobOptions } from "../../types/importGlob"; +import type { IncomingMessage } from 'node:http'; +import { InferCustomEventPayload } from "../../types/customEvent"; +import type { InputOption } from 'rollup'; +import type { InputOptions } from 'rollup'; +import { InvalidatePayload } from "../../types/customEvent"; +import { KnownAsTypeMap } from "../../types/importGlob"; +import type { LoadResult } from 'rollup'; + +import type { ModuleFormat } from 'rollup'; +import type { ModuleInfo } from 'rollup'; +import type * as net from 'node:net'; +import type { ObjectHook } from 'rollup'; +import type { OutgoingHttpHeaders } from 'node:http'; +import type { OutputBundle } from 'rollup'; +import type { OutputChunk } from 'rollup'; +import type { PartialResolvedId } from 'rollup'; +import type { Plugin as Plugin_3 } from 'rollup'; +import type { PluginContext } from 'rollup'; +import type { PluginHooks } from 'rollup'; +import type * as PostCSS from 'postcss'; +import { PrunePayload } from "../../types/hmrPayload"; +import type { ResolveIdResult } from 'rollup'; +import type { RollupError } from 'rollup'; +import type { RollupOptions } from 'rollup'; +import type { RollupOutput } from 'rollup'; +import { VERSION as rollupVersion } from 'rollup'; +import type { RollupWatcher } from 'rollup'; +import type { SecureContextOptions } from 'node:tls'; +import type { Server } from 'node:http'; +import type { Server as Server_2 } from 'node:https'; +import type { ServerOptions as ServerOptions_2 } from 'node:https'; +import type { ServerResponse } from 'node:http'; +import type { SourceDescription } from 'rollup'; +import type { SourceMap } from 'rollup'; +import type { SourceMapInput } from 'rollup'; +import type * as stream from 'node:stream'; +import type { TransformPluginContext } from 'rollup'; +import type { TransformResult as TransformResult_2 } from 'rollup'; +import type { TransformResult as TransformResult_3 } from 'esbuild'; +import { Update } from "../../types/hmrPayload"; +import { UpdatePayload } from "../../types/hmrPayload"; +import type * as url from 'node:url'; +import type { URL as URL_2 } from 'node:url'; +import type { WatcherOptions } from 'rollup'; +import type { ZlibOptions } from 'node:zlib'; + +export declare interface Alias { + find: string | RegExp + replacement: string + /** + * Instructs the plugin to use an alternative resolving algorithm, + * rather than the Rollup's resolver. + * @default null + */ + customResolver?: ResolverFunction | ResolverObject | null +} + +/** + * Specifies an `Object`, or an `Array` of `Object`, + * which defines aliases used to replace values in `import` or `require` statements. + * With either format, the order of the entries is important, + * in that the first defined rules are applied first. + * + * This is passed to \@rollup/plugin-alias as the "entries" field + * https://github.com/rollup/plugins/tree/master/packages/alias#entries + */ +export declare type AliasOptions = readonly Alias[] | { [find: string]: string } + +export declare type AnymatchFn = (testString: string) => boolean + +export declare type AnymatchPattern = string | RegExp | AnymatchFn + +/** + * spa: include SPA fallback middleware and configure sirv with `single: true` in preview + * + * mpa: only include non-SPA HTML middlewares + * + * custom: don't include HTML middlewares + */ +export declare type AppType = 'spa' | 'mpa' | 'custom'; + +export declare 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 +} + +/** + * Bundles the app for production. + * Returns a Promise containing the build result. + */ +export declare function build(inlineConfig?: InlineConfig): Promise; + +export declare interface BuildOptions { + /** + * Compatibility transform target. The transform is performed with esbuild + * and the lowest supported target is es2015/es6. Note this only handles + * syntax transformation and does not cover polyfills (except for dynamic + * import) + * + * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules, + * transpile targeting browsers that natively support dynamic es module imports. + * https://caniuse.com/es6-module-dynamic-import + * + * Another special value is 'esnext' - which only performs minimal transpiling + * (for minification compat) and assumes native dynamic imports support. + * + * For custom targets, see https://esbuild.github.io/api/#target and + * https://esbuild.github.io/content-types/#javascript for more details. + */ + target?: 'modules' | EsbuildTransformOptions['target'] | false; + /** + * whether to inject module preload polyfill. + * Note: does not apply to library mode. + * @default true + * @deprecated use `modulePreload.polyfill` instead + */ + polyfillModulePreload?: boolean; + /** + * Configure module preload + * Note: does not apply to library mode. + * @default true + */ + modulePreload?: boolean | ModulePreloadOptions; + /** + * Directory relative from `root` where build output will be placed. If the + * directory exists, it will be removed before the build. + * @default 'dist' + */ + outDir?: string; + /** + * Directory relative from `outDir` where the built js/css/image assets will + * be placed. + * @default 'assets' + */ + assetsDir?: string; + /** + * Static asset files smaller than this number (in bytes) will be inlined as + * base64 strings. Default limit is `4096` (4kb). Set to `0` to disable. + * @default 4096 + */ + assetsInlineLimit?: number; + /** + * Whether to code-split CSS. When enabled, CSS in async chunks will be + * inlined as strings in the chunk and inserted via dynamically created + * style tags when the chunk is loaded. + * @default true + */ + cssCodeSplit?: boolean; + /** + * An optional separate target for CSS minification. + * As esbuild only supports configuring targets to mainstream + * browsers, users may need this option when they are targeting + * a niche browser that comes with most modern JavaScript features + * but has poor CSS support, e.g. Android WeChat WebView, which + * doesn't support the #RGBA syntax. + */ + cssTarget?: EsbuildTransformOptions['target'] | false; + /** + * If `true`, a separate sourcemap file will be created. If 'inline', the + * sourcemap will be appended to the resulting output file as data URI. + * 'hidden' works like `true` except that the corresponding sourcemap + * comments in the bundled files are suppressed. + * @default false + */ + sourcemap?: boolean | 'inline' | 'hidden'; + /** + * Set to `false` to disable minification, or specify the minifier to use. + * Available options are 'terser' or 'esbuild'. + * @default 'esbuild' + */ + minify?: boolean | 'terser' | 'esbuild'; + /** + * Options for terser + * https://terser.org/docs/api-reference#minify-options + */ + terserOptions?: Terser.MinifyOptions; + /** + * Will be merged with internal rollup options. + * https://rollupjs.org/guide/en/#big-list-of-options + */ + rollupOptions?: RollupOptions; + /** + * Options to pass on to `@rollup/plugin-commonjs` + */ + commonjsOptions?: RollupCommonJSOptions; + /** + * Options to pass on to `@rollup/plugin-dynamic-import-vars` + */ + dynamicImportVarsOptions?: RollupDynamicImportVarsOptions; + /** + * Whether to write bundle to disk + * @default true + */ + write?: boolean; + /** + * Empty outDir on write. + * @default true when outDir is a sub directory of project root + */ + emptyOutDir?: boolean | null; + /** + * Copy the public directory to outDir on write. + * @default true + * @experimental + */ + copyPublicDir?: boolean; + /** + * Whether to emit a manifest.json under assets dir to map hash-less filenames + * to their hashed versions. Useful when you want to generate your own HTML + * instead of using the one generated by Vite. + * + * Example: + * + * ```json + * { + * "main.js": { + * "file": "main.68fe3fad.js", + * "css": "main.e6b63442.css", + * "imports": [...], + * "dynamicImports": [...] + * } + * } + * ``` + * @default false + */ + manifest?: boolean | string; + /** + * Build in library mode. The value should be the global name of the lib in + * UMD mode. This will produce esm + cjs + umd bundle formats with default + * configurations that are suitable for distributing libraries. + */ + lib?: LibraryOptions | false; + /** + * Produce SSR oriented build. Note this requires specifying SSR entry via + * `rollupOptions.input`. + */ + ssr?: boolean | string; + /** + * Generate SSR manifest for determining style links and asset preload + * directives in production. + */ + ssrManifest?: boolean | string; + /** + * Set to false to disable reporting compressed chunk sizes. + * Can slightly improve build speed. + */ + reportCompressedSize?: boolean; + /** + * Adjust chunk size warning limit (in kbs). + * @default 500 + */ + chunkSizeWarningLimit?: number; + /** + * Rollup watch options + * https://rollupjs.org/guide/en/#watchoptions + */ + watch?: WatcherOptions | null; +} + +export declare interface ChunkMetadata { + importedAssets: Set; + importedCss: Set; +} + +export declare interface CommonServerOptions { + /** + * Specify server port. Note if the port is already being used, Vite will + * automatically try the next available port so this may not be the actual + * port the server ends up listening on. + */ + port?: number; + /** + * If enabled, vite will exit if specified port is already in use + */ + strictPort?: boolean; + /** + * Specify which IP addresses the server should listen on. + * Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses. + */ + host?: string | boolean; + /** + * Enable TLS + HTTP/2. + * Note: this downgrades to TLS only when the proxy option is also used. + */ + https?: boolean | ServerOptions_2; + /** + * Open browser window on startup + */ + open?: boolean | string; + /** + * Configure custom proxy rules for the dev server. Expects an object + * of `{ key: options }` pairs. + * Uses [`http-proxy`](https://github.com/http-party/node-http-proxy). + * Full options [here](https://github.com/http-party/node-http-proxy#options). + * + * Example `vite.config.js`: + * ``` js + * module.exports = { + * proxy: { + * // string shorthand + * '/foo': 'http://localhost:4567/foo', + * // with options + * '/api': { + * target: 'http://jsonplaceholder.typicode.com', + * changeOrigin: true, + * rewrite: path => path.replace(/^\/api/, '') + * } + * } + * } + * ``` + */ + proxy?: Record; + /** + * Configure CORS for the dev server. + * Uses https://github.com/expressjs/cors. + * Set to `true` to allow all methods from any origin, or configure separately + * using an object. + */ + cors?: CorsOptions | boolean; + /** + * Specify server response headers. + */ + headers?: OutgoingHttpHeaders; +} + +export declare interface ConfigEnv { + command: 'build' | 'serve'; + mode: string; + /** + * @experimental + */ + ssrBuild?: boolean; +} + +export declare namespace Connect { + export type ServerHandle = HandleFunction | http.Server + + export class IncomingMessage extends http.IncomingMessage { + originalUrl?: http.IncomingMessage['url'] | undefined + } + + export type NextFunction = (err?: any) => void + + export type SimpleHandleFunction = ( + req: IncomingMessage, + res: http.ServerResponse + ) => void + export type NextHandleFunction = ( + req: IncomingMessage, + res: http.ServerResponse, + next: NextFunction + ) => void + export type ErrorHandleFunction = ( + err: any, + req: IncomingMessage, + res: http.ServerResponse, + next: NextFunction + ) => void + export type HandleFunction = + | SimpleHandleFunction + | NextHandleFunction + | ErrorHandleFunction + + export interface ServerStackItem { + route: string + handle: ServerHandle + } + + export interface Server extends NodeJS.EventEmitter { + (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void + + route: string + stack: ServerStackItem[] + + /** + * Utilize the given middleware `handle` to the given `route`, + * defaulting to _/_. This "route" is the mount-point for the + * middleware, when given a value other than _/_ the middleware + * is only effective when that segment is present in the request's + * pathname. + * + * For example if we were to mount a function at _/admin_, it would + * be invoked on _/admin_, and _/admin/settings_, however it would + * not be invoked for _/_, or _/posts_. + */ + use(fn: NextHandleFunction): Server + use(fn: HandleFunction): Server + use(route: string, fn: NextHandleFunction): Server + use(route: string, fn: HandleFunction): Server + + /** + * Handle server requests, punting them down + * the middleware stack. + */ + handle( + req: http.IncomingMessage, + res: http.ServerResponse, + next: Function + ): void + + /** + * Listen for connections. + * + * This method takes the same arguments + * as node's `http.Server#listen()`. + * + * HTTP and HTTPS: + * + * If you run your application both as HTTP + * and HTTPS you may wrap them individually, + * since your Connect "server" is really just + * a JavaScript `Function`. + * + * var connect = require('connect') + * , http = require('http') + * , https = require('https'); + * + * var app = connect(); + * + * http.createServer(app).listen(80); + * https.createServer(options, app).listen(443); + */ + listen( + port: number, + hostname?: string, + backlog?: number, + callback?: Function + ): http.Server + listen(port: number, hostname?: string, callback?: Function): http.Server + listen(path: string, callback?: Function): http.Server + listen(handle: any, listeningListener?: Function): http.Server + } +} + +export { ConnectedPayload } + +/** + * https://github.com/expressjs/cors#configuration-options + */ +export declare interface CorsOptions { + origin?: CorsOrigin | ((origin: string, cb: (err: Error, origins: CorsOrigin) => void) => void); + methods?: string | string[]; + allowedHeaders?: string | string[]; + exposedHeaders?: string | string[]; + credentials?: boolean; + maxAge?: number; + preflightContinue?: boolean; + optionsSuccessStatus?: number; +} + +export declare type CorsOrigin = boolean | string | RegExp | (string | RegExp)[]; + +export declare const createFilter: (include?: FilterPattern | undefined, exclude?: FilterPattern | undefined, options?: { + resolve?: string | false | null | undefined; +} | undefined) => (id: string | unknown) => boolean; + +export declare function createLogger(level?: LogLevel, options?: LoggerOptions): Logger; + +export declare function createServer(inlineConfig?: InlineConfig): Promise; + +export declare interface CSSModulesOptions { + getJSON?: (cssFileName: string, json: Record, outputFileName: string) => void; + scopeBehaviour?: 'global' | 'local'; + globalModulePaths?: RegExp[]; + generateScopedName?: string | ((name: string, filename: string, css: string) => string); + hashPrefix?: string; + /** + * default: null + */ + localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | null; +} + +export declare interface CSSOptions { + /** + * https://github.com/css-modules/postcss-modules + */ + modules?: CSSModulesOptions | false; + preprocessorOptions?: Record; + postcss?: string | (PostCSS.ProcessOptions & { + plugins?: PostCSS.AcceptedPlugin[]; + }); + /** + * Enables css sourcemaps during dev + * @default false + * @experimental + */ + devSourcemap?: boolean; +} + +export { CustomEventMap } + +export { CustomPayload } + +/** + * Type helper to make it easier to use vite.config.ts + * accepts a direct {@link UserConfig} object, or a function that returns it. + * The function receives a {@link ConfigEnv} object that exposes two properties: + * `command` (either `'build'` or `'serve'`), and `mode`. + */ +export declare function defineConfig(config: UserConfigExport): UserConfigExport; + +export declare interface DepOptimizationConfig { + /** + * Force optimize listed dependencies (must be resolvable import paths, + * cannot be globs). + */ + include?: string[]; + /** + * Do not optimize these dependencies (must be resolvable import paths, + * cannot be globs). + */ + exclude?: string[]; + /** + * Force ESM interop when importing for these dependencies. Some legacy + * packages advertise themselves as ESM but use `require` internally + * @experimental + */ + needsInterop?: string[]; + /** + * Options to pass to esbuild during the dep scanning and optimization + * + * Certain options are omitted since changing them would not be compatible + * with Vite's dep optimization. + * + * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option + * - `plugins` are merged with Vite's dep plugin + * + * https://esbuild.github.io/api + */ + esbuildOptions?: Omit; + /** + * List of file extensions that can be optimized. A corresponding esbuild + * plugin must exist to handle the specific extension. + * + * By default, Vite can optimize `.mjs`, `.js`, `.ts`, and `.mts` files. This option + * allows specifying additional extensions. + * + * @experimental + */ + extensions?: string[]; + /** + * Disables dependencies optimizations, true disables the optimizer during + * build and dev. Pass 'build' or 'dev' to only disable the optimizer in + * one of the modes. Deps optimization is enabled by default in dev only. + * @default 'build' + * @experimental + */ + disabled?: boolean | 'build' | 'dev'; +} + +export declare interface DepOptimizationMetadata { + /** + * The main hash is determined by user config and dependency lockfiles. + * This is checked on server startup to avoid unnecessary re-bundles. + */ + hash: string; + /** + * The browser hash is determined by the main hash plus additional dependencies + * discovered at runtime. This is used to invalidate browser requests to + * optimized deps. + */ + browserHash: string; + /** + * Metadata for each already optimized dependency + */ + optimized: Record; + /** + * Metadata for non-entry optimized chunks and dynamic imports + */ + chunks: Record; + /** + * Metadata for each newly discovered dependency after processing + */ + discovered: Record; + /** + * OptimizedDepInfo list + */ + depInfoList: OptimizedDepInfo[]; +} + +export declare type DepOptimizationOptions = DepOptimizationConfig & { + /** + * By default, Vite will crawl your `index.html` to detect dependencies that + * need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite + * will crawl those entry points instead. + * + * If neither of these fit your needs, you can specify custom entries using + * this option - the value should be a fast-glob pattern or array of patterns + * (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from + * vite project root. This will overwrite default entries inference. + */ + entries?: string | string[]; + /** + * Force dep pre-optimization regardless of whether deps have changed. + * @experimental + */ + force?: boolean; +}; + +export declare interface DepOptimizationProcessing { + promise: Promise; + resolve: () => void; +} + +export declare interface DepOptimizationResult { + metadata: DepOptimizationMetadata; + /** + * When doing a re-run, if there are newly discovered dependencies + * the page reload will be delayed until the next rerun so we need + * to be able to discard the result + */ + commit: () => Promise; + cancel: () => void; +} + +export declare interface DepsOptimizer { + metadata: DepOptimizationMetadata; + scanProcessing?: Promise; + registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo; + run: () => void; + isOptimizedDepFile: (id: string) => boolean; + isOptimizedDepUrl: (url: string) => boolean; + getOptimizedDepId: (depInfo: OptimizedDepInfo) => string; + delayDepsOptimizerUntil: (id: string, done: () => Promise) => void; + registerWorkersSource: (id: string) => void; + resetRegisteredIds: () => void; + ensureFirstRun: () => void; + close: () => Promise; + options: DepOptimizationOptions; +} + +export { ErrorPayload } + +export declare interface ESBuildOptions extends EsbuildTransformOptions { + include?: string | RegExp | string[] | RegExp[]; + exclude?: string | RegExp | string[] | RegExp[]; + jsxInject?: string; + /** + * This option is not respected. Use `build.minify` instead. + */ + minify?: never; +} + +export { EsbuildTransformOptions } + +export declare type ESBuildTransformResult = Omit & { + map: SourceMap; +}; + +export { esbuildVersion } + +export declare interface ExperimentalOptions { + /** + * Append fake `&lang.(ext)` when queries are specified, to preserve the file extension for following plugins to process. + * + * @experimental + * @default false + */ + importGlobRestoreExtension?: boolean; + /** + * Allow finegrain control over assets and public files paths + * + * @experimental + */ + renderBuiltUrl?: RenderBuiltAssetUrl; + /** + * Enables support of HMR partial accept via `import.meta.hot.acceptExports`. + * + * @experimental + * @default false + */ + hmrPartialAccept?: boolean; +} + +export declare type ExportsData = { + hasImports: boolean; + exports: readonly string[]; + facade: boolean; + hasReExports?: boolean; + jsxLoader?: boolean; +}; + +export declare interface FileSystemServeOptions { + /** + * Strictly restrict file accessing outside of allowing paths. + * + * Set to `false` to disable the warning + * + * @default true + */ + strict?: boolean; + /** + * Restrict accessing files outside the allowed directories. + * + * Accepts absolute path or a path relative to project root. + * Will try to search up for workspace root by default. + */ + allow?: string[]; + /** + * Restrict accessing files that matches the patterns. + * + * This will have higher priority than `allow`. + * picomatch patterns are supported. + * + * @default ['.env', '.env.*', '*.crt', '*.pem'] + */ + deny?: string[]; +} + +/** + * Inlined to keep `@rollup/pluginutils` in devDependencies + */ +export declare type FilterPattern = ReadonlyArray | string | RegExp | null; + +export declare function formatPostcssSourceMap(rawMap: ExistingRawSourceMap, file: string): Promise; + +export declare 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 +} + +export { FullReloadPayload } + +export { GeneralImportGlobOptions } + +export declare function getDepOptimizationConfig(config: ResolvedConfig, ssr: boolean): DepOptimizationConfig; + +export declare interface HmrContext { + file: string; + timestamp: number; + modules: Array; + read: () => string | Promise; + server: ViteDevServer; +} + +export declare interface HmrOptions { + protocol?: string; + host?: string; + port?: number; + clientPort?: number; + path?: string; + timeout?: number; + overlay?: boolean; + server?: Server; +} + +export { HMRPayload } + +export declare type HookHandler = T extends ObjectHook ? H : T; + +export declare interface HtmlTagDescriptor { + tag: string; + attrs?: Record; + children?: string | HtmlTagDescriptor[]; + /** + * default: 'head-prepend' + */ + injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend'; +} + +export declare namespace HttpProxy { + export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed + + export type ProxyTargetUrl = string | Partial + + export interface ProxyTargetDetailed { + host: string + port: number + protocol?: string | undefined + hostname?: string | undefined + socketPath?: string | undefined + key?: string | undefined + passphrase?: string | undefined + pfx?: Buffer | string | undefined + cert?: string | undefined + ca?: string | undefined + ciphers?: string | undefined + secureProtocol?: string | undefined + } + + export type ErrorCallback = ( + err: Error, + req: http.IncomingMessage, + res: http.ServerResponse, + target?: ProxyTargetUrl + ) => void + + export class Server extends events.EventEmitter { + /** + * Creates the proxy server with specified options. + * @param options - Config object passed to the proxy + */ + constructor(options?: ServerOptions) + + /** + * Used for proxying regular HTTP(S) requests + * @param req - Client request. + * @param res - Client response. + * @param options - Additional options. + */ + web( + req: http.IncomingMessage, + res: http.ServerResponse, + options?: ServerOptions, + callback?: ErrorCallback + ): void + + /** + * Used for proxying regular HTTP(S) requests + * @param req - Client request. + * @param socket - Client socket. + * @param head - Client head. + * @param options - Additional options. + */ + ws( + req: http.IncomingMessage, + socket: unknown, + head: unknown, + options?: ServerOptions, + callback?: ErrorCallback + ): void + + /** + * A function that wraps the object in a webserver, for your convenience + * @param port - Port to listen on + */ + listen(port: number): Server + + /** + * A function that closes the inner webserver and stops listening on given port + */ + close(callback?: () => void): void + + /** + * Creates the proxy server with specified options. + * @param options - Config object passed to the proxy + * @returns Proxy object with handlers for `ws` and `web` requests + */ + static createProxyServer(options?: ServerOptions): Server + + /** + * Creates the proxy server with specified options. + * @param options - Config object passed to the proxy + * @returns Proxy object with handlers for `ws` and `web` requests + */ + static createServer(options?: ServerOptions): Server + + /** + * Creates the proxy server with specified options. + * @param options - Config object passed to the proxy + * @returns Proxy object with handlers for `ws` and `web` requests + */ + static createProxy(options?: ServerOptions): Server + + addListener(event: string, listener: () => void): this + on(event: string, listener: () => void): this + on(event: 'error', listener: ErrorCallback): this + on( + event: 'start', + listener: ( + req: http.IncomingMessage, + res: http.ServerResponse, + target: ProxyTargetUrl + ) => void + ): this + on( + event: 'proxyReq', + listener: ( + proxyReq: http.ClientRequest, + req: http.IncomingMessage, + res: http.ServerResponse, + options: ServerOptions + ) => void + ): this + on( + event: 'proxyRes', + listener: ( + proxyRes: http.IncomingMessage, + req: http.IncomingMessage, + res: http.ServerResponse + ) => void + ): this + on( + event: 'proxyReqWs', + listener: ( + proxyReq: http.ClientRequest, + req: http.IncomingMessage, + socket: net.Socket, + options: ServerOptions, + head: any + ) => void + ): this + on( + event: 'econnreset', + listener: ( + err: Error, + req: http.IncomingMessage, + res: http.ServerResponse, + target: ProxyTargetUrl + ) => void + ): this + on( + event: 'end', + listener: ( + req: http.IncomingMessage, + res: http.ServerResponse, + proxyRes: http.IncomingMessage + ) => void + ): this + on( + event: 'close', + listener: ( + proxyRes: http.IncomingMessage, + proxySocket: net.Socket, + proxyHead: any + ) => void + ): this + + once(event: string, listener: () => void): this + removeListener(event: string, listener: () => void): this + removeAllListeners(event?: string): this + getMaxListeners(): number + setMaxListeners(n: number): this + listeners(event: string): Array<() => void> + emit(event: string, ...args: any[]): boolean + listenerCount(type: string): number + } + + export interface ServerOptions { + /** URL string to be parsed with the url module. */ + target?: ProxyTarget | undefined + /** URL string to be parsed with the url module. */ + forward?: ProxyTargetUrl | undefined + /** Object to be passed to http(s).request. */ + agent?: any + /** Object to be passed to https.createServer(). */ + ssl?: any + /** If you want to proxy websockets. */ + ws?: boolean | undefined + /** Adds x- forward headers. */ + xfwd?: boolean | undefined + /** Verify SSL certificate. */ + secure?: boolean | undefined + /** Explicitly specify if we are proxying to another proxy. */ + toProxy?: boolean | undefined + /** Specify whether you want to prepend the target's path to the proxy path. */ + prependPath?: boolean | undefined + /** Specify whether you want to ignore the proxy path of the incoming request. */ + ignorePath?: boolean | undefined + /** Local interface string to bind for outgoing connections. */ + localAddress?: string | undefined + /** Changes the origin of the host header to the target URL. */ + changeOrigin?: boolean | undefined + /** specify whether you want to keep letter case of response header key */ + preserveHeaderKeyCase?: boolean | undefined + /** Basic authentication i.e. 'user:password' to compute an Authorization header. */ + auth?: string | undefined + /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */ + hostRewrite?: string | undefined + /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */ + autoRewrite?: boolean | undefined + /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */ + protocolRewrite?: string | undefined + /** rewrites domain of set-cookie headers. */ + cookieDomainRewrite?: + | false + | string + | { [oldDomain: string]: string } + | undefined + /** rewrites path of set-cookie headers. Default: false */ + cookiePathRewrite?: + | false + | string + | { [oldPath: string]: string } + | undefined + /** object with extra headers to be added to target requests. */ + headers?: { [header: string]: string } | undefined + /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */ + proxyTimeout?: number | undefined + /** Timeout (in milliseconds) for incoming requests */ + timeout?: number | undefined + /** Specify whether you want to follow redirects. Default: false */ + followRedirects?: boolean | undefined + /** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */ + selfHandleResponse?: boolean | undefined + /** Buffer */ + buffer?: stream.Stream | undefined + } +} + +export { ImportGlobEagerFunction } + +export { ImportGlobFunction } + +export { ImportGlobOptions } + +export declare type IndexHtmlTransform = IndexHtmlTransformHook | { + enforce?: 'pre' | 'post'; + transform: IndexHtmlTransformHook; +}; + +export declare interface IndexHtmlTransformContext { + /** + * public path when served + */ + path: string; + /** + * filename on disk + */ + filename: string; + server?: ViteDevServer; + bundle?: OutputBundle; + chunk?: OutputChunk; + originalUrl?: string; +} + +export declare type IndexHtmlTransformHook = (this: void, html: string, ctx: IndexHtmlTransformContext) => IndexHtmlTransformResult | void | Promise; + +export declare type IndexHtmlTransformResult = string | HtmlTagDescriptor[] | { + html: string; + tags: HtmlTagDescriptor[]; +}; + +export { InferCustomEventPayload } + +export declare interface InlineConfig extends UserConfig { + configFile?: string | false; + envFile?: false; +} + +export declare interface InternalResolveOptions extends Required { + root: string; + isBuild: boolean; + isProduction: boolean; + ssrConfig?: SSROptions; + packageCache?: PackageCache; + /** + * src code mode also attempts the following: + * - resolving /xxx as URLs + * - resolving bare imports from optimized deps + */ + asSrc?: boolean; + tryIndex?: boolean; + tryPrefix?: string; + skipPackageJson?: boolean; + preferRelative?: boolean; + isRequire?: boolean; + isFromTsImporter?: boolean; + tryEsmOnly?: boolean; + scan?: boolean; + ssrOptimizeCheck?: boolean; + getDepsOptimizer?: (ssr: boolean) => DepsOptimizer | undefined; + shouldExternalize?: (id: string) => boolean | undefined; + isHookNodeResolve?: boolean; +} + +export { InvalidatePayload } + +export declare function isDepsOptimizerEnabled(config: ResolvedConfig, ssr: boolean): boolean; + +export declare interface JsonOptions { + /** + * Generate a named export for every property of the JSON object + * @default true + */ + namedExports?: boolean; + /** + * Generate performant output as JSON.parse("stringified"). + * Enabling this will disable namedExports. + * @default false + */ + stringify?: boolean; +} + +export { KnownAsTypeMap } + +export declare interface LegacyOptions { + /** + * Revert vite build --ssr to the v2.9 strategy. Use CJS SSR build and v2.9 externalization heuristics + * + * @experimental + * @deprecated + * @default false + */ + buildSsrCjsExternalHeuristics?: boolean; +} + +export declare type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife'; + +export declare interface LibraryOptions { + /** + * Path of library entry + */ + entry: InputOption; + /** + * The name of the exposed global variable. Required when the `formats` option includes + * `umd` or `iife` + */ + name?: string; + /** + * Output bundle formats + * @default ['es', 'umd'] + */ + formats?: LibraryFormats[]; + /** + * The name of the package file output. The default file name is the name option + * of the project package.json. It can also be defined as a function taking the + * format as an argument. + */ + fileName?: string | ((format: ModuleFormat, entryName: string) => string); +} + +export declare function loadConfigFromFile(configEnv: ConfigEnv, configFile?: string, configRoot?: string, logLevel?: LogLevel): Promise<{ + path: string; + config: UserConfig; + dependencies: string[]; +} | null>; + +export declare function loadEnv(mode: string, envDir: string, prefixes?: string | string[]): Record; + +export declare interface LogErrorOptions extends LogOptions { + error?: Error | RollupError | null; +} + +export declare interface Logger { + info(msg: string, options?: LogOptions): void; + warn(msg: string, options?: LogOptions): void; + warnOnce(msg: string, options?: LogOptions): void; + error(msg: string, options?: LogErrorOptions): void; + clearScreen(type: LogType): void; + hasErrorLogged(error: Error | RollupError): boolean; + hasWarned: boolean; +} + +export declare interface LoggerOptions { + prefix?: string; + allowClearScreen?: boolean; + customLogger?: Logger; +} + +export declare type LogLevel = LogType | 'silent'; + +export declare interface LogOptions { + clear?: boolean; + timestamp?: boolean; +} + +export declare type LogType = 'error' | 'warn' | 'info'; + +export declare type Manifest = Record; + +export declare interface ManifestChunk { + src?: string; + file: string; + css?: string[]; + assets?: string[]; + isEntry?: boolean; + isDynamicEntry?: boolean; + imports?: string[]; + dynamicImports?: string[]; +} + +export declare type MapToFunction = T extends Function ? T : never + +export declare type Matcher = AnymatchPattern | AnymatchPattern[] + +export declare function mergeAlias(a?: AliasOptions, b?: AliasOptions): AliasOptions | undefined; + +export declare function mergeConfig(defaults: Record, overrides: Record, isRoot?: boolean): Record; + +export declare class ModuleGraph { + private resolveId; + urlToModuleMap: Map; + idToModuleMap: Map; + fileToModulesMap: Map>; + safeModulesPath: Set; + constructor(resolveId: (url: string, ssr: boolean) => Promise); + getModuleByUrl(rawUrl: string, ssr?: boolean): Promise; + getModuleById(id: string): ModuleNode | undefined; + getModulesByFile(file: string): Set | undefined; + onFileChange(file: string): void; + invalidateModule(mod: ModuleNode, seen?: Set, timestamp?: number): void; + invalidateAll(): void; + /** + * Update the module graph based on a module's updated imports information + * If there are dependencies that no longer have any importers, they are + * returned as a Set. + */ + updateModuleInfo(mod: ModuleNode, importedModules: Set, importedBindings: Map> | null, acceptedModules: Set, acceptedExports: Set | null, isSelfAccepting: boolean, ssr?: boolean): Promise | undefined>; + ensureEntryFromUrl(rawUrl: string, ssr?: boolean, setIsSelfAccepting?: boolean): Promise; + createFileOnlyEntry(file: string): ModuleNode; + resolveUrl(url: string, ssr?: boolean): Promise; +} + +export declare class ModuleNode { + /** + * Public served url path, starts with / + */ + url: string; + /** + * Resolved file system path + query + */ + id: string | null; + file: string | null; + type: 'js' | 'css'; + info?: ModuleInfo; + meta?: Record; + importers: Set; + importedModules: Set; + acceptedHmrDeps: Set; + acceptedHmrExports: Set | null; + importedBindings: Map> | null; + isSelfAccepting?: boolean; + transformResult: TransformResult | null; + ssrTransformResult: TransformResult | null; + ssrModule: Record | null; + ssrError: Error | null; + lastHMRTimestamp: number; + lastInvalidationTimestamp: number; + /** + * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870 + */ + constructor(url: string, setIsSelfAccepting?: boolean); +} + +export declare interface ModulePreloadOptions { + /** + * Whether to inject a module preload polyfill. + * Note: does not apply to library mode. + * @default true + */ + polyfill?: boolean; + /** + * Resolve the list of dependencies to preload for a given dynamic import + * @experimental + */ + resolveDependencies?: ResolveModulePreloadDependenciesFn; +} + +export declare function normalizePath(id: string): string; + +export declare interface OptimizedDepInfo { + id: string; + file: string; + src?: string; + needsInterop?: boolean; + browserHash?: string; + fileHash?: string; + /** + * During optimization, ids can still be resolved to their final location + * but the bundles may not yet be saved to disk + */ + processing?: Promise; + /** + * ExportData cache, discovered deps will parse the src entry to get exports + * data used both to define if interop is needed and when pre-bundling + */ + exportsData?: Promise; +} + +/** + * Scan and optimize dependencies within a project. + * Used by Vite CLI when running `vite optimize`. + */ +export declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean): Promise; + +/** Cache for package.json resolution and package.json contents */ +export declare type PackageCache = Map; + +export declare interface PackageData { + dir: string; + hasSideEffects: (id: string) => boolean | 'no-treeshake'; + webResolvedImports: Record; + nodeResolvedImports: Record; + setResolvedCache: (key: string, entry: string, targetWeb: boolean) => void; + getResolvedCache: (key: string, targetWeb: boolean) => string | undefined; + data: { + [field: string]: any; + name: string; + type: string; + version: string; + main: string; + module: string; + browser: string | Record; + exports: string | Record | string[]; + dependencies: Record; + }; +} + +/** + * Vite plugins extends the Rollup plugin interface with a few extra + * vite-specific options. A valid vite plugin is also a valid Rollup plugin. + * On the contrary, a Rollup plugin may or may NOT be a valid vite universal + * plugin, since some Rollup features do not make sense in an unbundled + * dev server context. That said, as long as a rollup plugin doesn't have strong + * coupling between its bundle phase and output phase hooks then it should + * just work (that means, most of them). + * + * By default, the plugins are run during both serve and build. When a plugin + * is applied during serve, it will only run **non output plugin hooks** (see + * rollup type definition of {@link rollup#PluginHooks}). You can think of the + * dev server as only running `const bundle = rollup.rollup()` but never calling + * `bundle.generate()`. + * + * A plugin that expects to have different behavior depending on serve/build can + * export a factory function that receives the command being run via options. + * + * If a plugin should be applied only for server or build, a function format + * config file can be used to conditional determine the plugins to use. + */ +declare interface Plugin_2 extends Plugin_3 { + /** + * Enforce plugin invocation tier similar to webpack loaders. + * + * Plugin invocation order: + * - alias resolution + * - `enforce: 'pre'` plugins + * - vite core plugins + * - normal plugins + * - vite build plugins + * - `enforce: 'post'` plugins + * - vite build post plugins + */ + enforce?: 'pre' | 'post'; + /** + * Apply the plugin only for serve or build, or on certain conditions. + */ + apply?: 'serve' | 'build' | ((this: void, config: UserConfig, env: ConfigEnv) => boolean); + /** + * Modify vite config before it's resolved. The hook can either mutate the + * passed-in config directly, or return a partial config object that will be + * deeply merged into existing config. + * + * Note: User plugins are resolved before running this hook so injecting other + * plugins inside the `config` hook will have no effect. + */ + config?: ObjectHook<(this: void, config: UserConfig, env: ConfigEnv) => UserConfig | null | void | Promise>; + /** + * Use this hook to read and store the final resolved vite config. + */ + configResolved?: ObjectHook<(this: void, config: ResolvedConfig) => void | Promise>; + /** + * Configure the vite server. The hook receives the {@link ViteDevServer} + * instance. This can also be used to store a reference to the server + * for use in other hooks. + * + * The hooks will be called before internal middlewares are applied. A hook + * can return a post hook that will be called after internal middlewares + * are applied. Hook can be async functions and will be called in series. + */ + configureServer?: ObjectHook; + /** + * Configure the preview server. The hook receives the connect server and + * its underlying http server. + * + * The hooks are called before other middlewares are applied. A hook can + * return a post hook that will be called after other middlewares are + * applied. Hooks can be async functions and will be called in series. + */ + configurePreviewServer?: ObjectHook; + /** + * Transform index.html. + * The hook receives the following arguments: + * + * - html: string + * - ctx?: vite.ServerContext (only present during serve) + * - bundle?: rollup.OutputBundle (only present during build) + * + * It can either return a transformed string, or a list of html tag + * descriptors that will be injected into the `` or ``. + * + * By default the transform is applied **after** vite's internal html + * transform. If you need to apply the transform before vite, use an object: + * `{ enforce: 'pre', transform: hook }` + */ + transformIndexHtml?: IndexHtmlTransform; + /** + * Perform custom handling of HMR updates. + * The handler receives a context containing changed filename, timestamp, a + * list of modules affected by the file change, and the dev server instance. + * + * - The hook can return a filtered list of modules to narrow down the update. + * e.g. for a Vue SFC, we can narrow down the part to update by comparing + * the descriptors. + * + * - The hook can also return an empty array and then perform custom updates + * by sending a custom hmr payload via server.ws.send(). + * + * - If the hook doesn't return a value, the hmr update will be performed as + * normal. + */ + handleHotUpdate?: ObjectHook<(this: void, ctx: HmrContext) => Array | void | Promise | void>>; + /** + * extend hooks with ssr flag + */ + resolveId?: ObjectHook<(this: PluginContext, source: string, importer: string | undefined, options: { + custom?: CustomPluginOptions; + ssr?: boolean; + /* Excluded from this release type: scan */ + isEntry: boolean; + }) => Promise | ResolveIdResult>; + load?: ObjectHook<(this: PluginContext, id: string, options?: { + ssr?: boolean; + }) => Promise | LoadResult>; + transform?: ObjectHook<(this: TransformPluginContext, code: string, id: string, options?: { + ssr?: boolean; + }) => Promise | TransformResult_2>; +} +export { Plugin_2 as Plugin } + +export declare interface PluginContainer { + options: InputOptions; + getModuleInfo(id: string): ModuleInfo | null; + buildStart(options: InputOptions): Promise; + resolveId(id: string, importer?: string, options?: { + custom?: CustomPluginOptions; + skip?: Set; + ssr?: boolean; + /* Excluded from this release type: scan */ + isEntry?: boolean; + }): Promise; + transform(code: string, id: string, options?: { + inMap?: SourceDescription['map']; + ssr?: boolean; + }): Promise; + load(id: string, options?: { + ssr?: boolean; + }): Promise; + close(): Promise; +} + +export declare interface PluginHookUtils { + getSortedPlugins: (hookName: keyof Plugin_2) => Plugin_2[]; + getSortedPluginHooks: (hookName: K) => NonNullable>[]; +} + +export declare type PluginOption = Plugin_2 | false | null | undefined | PluginOption[] | Promise; + +/** + * @experimental + */ +export declare function preprocessCSS(code: string, filename: string, config: ResolvedConfig): Promise; + +export declare interface PreprocessCSSResult { + code: string; + map?: SourceMapInput; + modules?: Record; + deps?: Set; +} + +/** + * Starts the Vite server in preview mode, to simulate a production deployment + */ +export declare function preview(inlineConfig?: InlineConfig): Promise; + +export declare interface PreviewOptions extends CommonServerOptions { +} + +export declare interface PreviewServer { + /** + * The resolved vite config object + */ + config: ResolvedConfig; + /** + * native Node http server instance + */ + httpServer: http.Server; + /** + * The resolved urls Vite prints on the CLI + */ + resolvedUrls: ResolvedServerUrls; + /** + * Print server urls + */ + printUrls(): void; +} + +export declare type PreviewServerHook = (this: void, server: { + middlewares: Connect.Server; + httpServer: http.Server; +}) => (() => void) | void | Promise<(() => void) | void>; + +export declare interface ProxyOptions extends HttpProxy.ServerOptions { + /** + * rewrite path + */ + rewrite?: (path: string) => string; + /** + * configure the proxy server (e.g. listen to events) + */ + configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void; + /** + * webpack-dev-server style bypass function + */ + bypass?: (req: http.IncomingMessage, res: http.ServerResponse, options: ProxyOptions) => void | null | undefined | false | string; +} + +export { PrunePayload } + +export declare type RenderBuiltAssetUrl = (filename: string, type: { + type: 'asset' | 'public'; + hostId: string; + hostType: 'js' | 'css' | 'html'; + ssr: boolean; +}) => string | { + relative?: boolean; + runtime?: string; +} | undefined; + +/** + * Resolve base url. Note that some users use Vite to build for non-web targets like + * electron or expects to deploy + */ +export declare function resolveBaseUrl(base: string | undefined, isBuild: boolean, logger: Logger): string; + +export declare function resolveConfig(inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode?: string): Promise; + +export declare interface ResolvedBuildOptions extends Required> { + modulePreload: false | ResolvedModulePreloadOptions; +} + +export declare type ResolvedConfig = Readonly & { + configFile: string | undefined; + configFileDependencies: string[]; + inlineConfig: InlineConfig; + root: string; + base: string; + publicDir: string; + cacheDir: string; + command: 'build' | 'serve'; + mode: string; + isWorker: boolean; + /* Excluded from this release type: mainConfig */ + isProduction: boolean; + env: Record; + resolve: Required & { + alias: Alias[]; + }; + plugins: readonly Plugin_2[]; + server: ResolvedServerOptions; + build: ResolvedBuildOptions; + preview: ResolvedPreviewOptions; + ssr: ResolvedSSROptions; + assetsInclude: (file: string) => boolean; + logger: Logger; + createResolver: (options?: Partial) => ResolveFn; + optimizeDeps: DepOptimizationOptions; + /* Excluded from this release type: packageCache */ + worker: ResolveWorkerOptions; + appType: AppType; + experimental: ExperimentalOptions; +} & PluginHookUtils>; + +export declare interface ResolvedModulePreloadOptions { + polyfill: boolean; + resolveDependencies?: ResolveModulePreloadDependenciesFn; +} + +export declare interface ResolvedPreviewOptions extends PreviewOptions { +} + +export declare interface ResolvedServerOptions extends ServerOptions { + fs: Required; + middlewareMode: boolean; +} + +export declare interface ResolvedServerUrls { + local: string[]; + network: string[]; +} + +export declare interface ResolvedSSROptions extends SSROptions { + target: SSRTarget; + format: SSRFormat; + optimizeDeps: SsrDepOptimizationOptions; +} + +export declare type ResolvedUrl = [ +url: string, +resolvedId: string, +meta: object | null | undefined +]; + +export declare function resolveEnvPrefix({ envPrefix }: UserConfig): string[]; + +export declare type ResolveFn = (id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean) => Promise; + +export declare type ResolveModulePreloadDependenciesFn = (filename: string, deps: string[], context: { + hostId: string; + hostType: 'html' | 'js'; +}) => string[]; + +export declare interface ResolveOptions { + mainFields?: string[]; + /** + * @deprecated In future, `mainFields` should be used instead. + * @default true + */ + browserField?: boolean; + conditions?: string[]; + extensions?: string[]; + dedupe?: string[]; + preserveSymlinks?: boolean; +} + +export declare function resolvePackageData(id: string, basedir: string, preserveSymlinks?: boolean, packageCache?: PackageCache): PackageData | null; + +export declare function resolvePackageEntry(id: string, { dir, data, setResolvedCache, getResolvedCache }: PackageData, targetWeb: boolean, options: InternalResolveOptions): string | undefined; + +export declare type ResolverFunction = MapToFunction + +export declare interface ResolverObject { + buildStart?: PluginHooks['buildStart'] + resolveId: ResolverFunction +} + +export declare interface ResolveWorkerOptions extends PluginHookUtils { + format: 'es' | 'iife'; + plugins: Plugin_2[]; + rollupOptions: RollupOptions; +} + +/** + * https://github.com/rollup/plugins/blob/master/packages/commonjs/types/index.d.ts + * + * This source code is licensed under the MIT license found in the + * LICENSE file at + * https://github.com/rollup/plugins/blob/master/LICENSE + */ +export declare interface RollupCommonJSOptions { + /** + * A minimatch pattern, or array of patterns, which specifies the files in + * the build the plugin should operate on. By default, all files with + * extension `".cjs"` or those in `extensions` are included, but you can + * narrow this list by only including specific files. These files will be + * analyzed and transpiled if either the analysis does not find ES module + * specific statements or `transformMixedEsModules` is `true`. + * @default undefined + */ + include?: string | RegExp | readonly (string | RegExp)[] + /** + * A minimatch pattern, or array of patterns, which specifies the files in + * the build the plugin should _ignore_. By default, all files with + * extensions other than those in `extensions` or `".cjs"` are ignored, but you + * can exclude additional files. See also the `include` option. + * @default undefined + */ + exclude?: string | RegExp | readonly (string | RegExp)[] + /** + * For extensionless imports, search for extensions other than .js in the + * order specified. Note that you need to make sure that non-JavaScript files + * are transpiled by another plugin first. + * @default [ '.js' ] + */ + extensions?: ReadonlyArray + /** + * If true then uses of `global` won't be dealt with by this plugin + * @default false + */ + ignoreGlobal?: boolean + /** + * If false, skips source map generation for CommonJS modules. This will + * improve performance. + * @default true + */ + sourceMap?: boolean + /** + * Some `require` calls cannot be resolved statically to be translated to + * imports. + * When this option is set to `false`, the generated code will either + * directly throw an error when such a call is encountered or, when + * `dynamicRequireTargets` is used, when such a call cannot be resolved with a + * configured dynamic require target. + * Setting this option to `true` will instead leave the `require` call in the + * code or use it as a fallback for `dynamicRequireTargets`. + * @default false + */ + ignoreDynamicRequires?: boolean + /** + * Instructs the plugin whether to enable mixed module transformations. This + * is useful in scenarios with modules that contain a mix of ES `import` + * statements and CommonJS `require` expressions. Set to `true` if `require` + * calls should be transformed to imports in mixed modules, or `false` if the + * `require` expressions should survive the transformation. The latter can be + * important if the code contains environment detection, or you are coding + * for an environment with special treatment for `require` calls such as + * ElectronJS. See also the `ignore` option. + * @default false + */ + transformMixedEsModules?: boolean + /** + * By default, this plugin will try to hoist `require` statements as imports + * to the top of each file. While this works well for many code bases and + * allows for very efficient ESM output, it does not perfectly capture + * CommonJS semantics as the order of side effects like log statements may + * change. But it is especially problematic when there are circular `require` + * calls between CommonJS modules as those often rely on the lazy execution of + * nested `require` calls. + * + * Setting this option to `true` will wrap all CommonJS files in functions + * which are executed when they are required for the first time, preserving + * NodeJS semantics. Note that this can have an impact on the size and + * performance of the generated code. + * + * The default value of `"auto"` will only wrap CommonJS files when they are + * part of a CommonJS dependency cycle, e.g. an index file that is required by + * many of its dependencies. All other CommonJS files are hoisted. This is the + * recommended setting for most code bases. + * + * `false` will entirely prevent wrapping and hoist all files. This may still + * work depending on the nature of cyclic dependencies but will often cause + * problems. + * + * You can also provide a minimatch pattern, or array of patterns, to only + * specify a subset of files which should be wrapped in functions for proper + * `require` semantics. + * + * `"debug"` works like `"auto"` but after bundling, it will display a warning + * containing a list of ids that have been wrapped which can be used as + * minimatch pattern for fine-tuning. + * @default "auto" + */ + strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[] + /** + * Sometimes you have to leave require statements unconverted. Pass an array + * containing the IDs or a `id => boolean` function. + * @default [] + */ + ignore?: ReadonlyArray | ((id: string) => boolean) + /** + * In most cases, where `require` calls are inside a `try-catch` clause, + * they should be left unconverted as it requires an optional dependency + * that may or may not be installed beside the rolled up package. + * Due to the conversion of `require` to a static `import` - the call is + * hoisted to the top of the file, outside of the `try-catch` clause. + * + * - `true`: All `require` calls inside a `try` will be left unconverted. + * - `false`: All `require` calls inside a `try` will be converted as if the + * `try-catch` clause is not there. + * - `remove`: Remove all `require` calls from inside any `try` block. + * - `string[]`: Pass an array containing the IDs to left unconverted. + * - `((id: string) => boolean|'remove')`: Pass a function that control + * individual IDs. + * + * @default false + */ + ignoreTryCatch?: + | boolean + | 'remove' + | ReadonlyArray + | ((id: string) => boolean | 'remove') + /** + * Controls how to render imports from external dependencies. By default, + * this plugin assumes that all external dependencies are CommonJS. This + * means they are rendered as default imports to be compatible with e.g. + * NodeJS where ES modules can only import a default export from a CommonJS + * dependency. + * + * If you set `esmExternals` to `true`, this plugins assumes that all + * external dependencies are ES modules and respect the + * `requireReturnsDefault` option. If that option is not set, they will be + * rendered as namespace imports. + * + * You can also supply an array of ids to be treated as ES modules, or a + * function that will be passed each external id to determine if it is an ES + * module. + * @default false + */ + esmExternals?: boolean | ReadonlyArray | ((id: string) => boolean) + /** + * Controls what is returned when requiring an ES module from a CommonJS file. + * When using the `esmExternals` option, this will also apply to external + * modules. By default, this plugin will render those imports as namespace + * imports i.e. + * + * ```js + * // input + * const foo = require('foo'); + * + * // output + * import * as foo from 'foo'; + * ``` + * + * However there are some situations where this may not be desired. + * For these situations, you can change Rollup's behaviour either globally or + * per module. To change it globally, set the `requireReturnsDefault` option + * to one of the following values: + * + * - `false`: This is the default, requiring an ES module returns its + * namespace. This is the only option that will also add a marker + * `__esModule: true` to the namespace to support interop patterns in + * CommonJS modules that are transpiled ES modules. + * - `"namespace"`: Like `false`, requiring an ES module returns its + * namespace, but the plugin does not add the `__esModule` marker and thus + * creates more efficient code. For external dependencies when using + * `esmExternals: true`, no additional interop code is generated. + * - `"auto"`: This is complementary to how `output.exports: "auto"` works in + * Rollup: If a module has a default export and no named exports, requiring + * that module returns the default export. In all other cases, the namespace + * is returned. For external dependencies when using `esmExternals: true`, a + * corresponding interop helper is added. + * - `"preferred"`: If a module has a default export, requiring that module + * always returns the default export, no matter whether additional named + * exports exist. This is similar to how previous versions of this plugin + * worked. Again for external dependencies when using `esmExternals: true`, + * an interop helper is added. + * - `true`: This will always try to return the default export on require + * without checking if it actually exists. This can throw at build time if + * there is no default export. This is how external dependencies are handled + * when `esmExternals` is not used. The advantage over the other options is + * that, like `false`, this does not add an interop helper for external + * dependencies, keeping the code lean. + * + * To change this for individual modules, you can supply a function for + * `requireReturnsDefault` instead. This function will then be called once for + * each required ES module or external dependency with the corresponding id + * and allows you to return different values for different modules. + * @default false + */ + requireReturnsDefault?: + | boolean + | 'auto' + | 'preferred' + | 'namespace' + | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace') + + /** + * @default "auto" + */ + defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto') + /** + * Some modules contain dynamic `require` calls, or require modules that + * contain circular dependencies, which are not handled well by static + * imports. Including those modules as `dynamicRequireTargets` will simulate a + * CommonJS (NodeJS-like) environment for them with support for dynamic + * dependencies. It also enables `strictRequires` for those modules. + * + * Note: In extreme cases, this feature may result in some paths being + * rendered as absolute in the final bundle. The plugin tries to avoid + * exposing paths from the local machine, but if you are `dynamicRequirePaths` + * with paths that are far away from your project's folder, that may require + * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`. + */ + dynamicRequireTargets?: string | ReadonlyArray + /** + * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory + * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/` + * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your + * home directory name. By default it uses the current working directory. + */ + dynamicRequireRoot?: string +} + +export declare interface RollupDynamicImportVarsOptions { + /** + * Files to include in this plugin (default all). + * @default [] + */ + include?: string | RegExp | (string | RegExp)[] + /** + * Files to exclude in this plugin (default none). + * @default [] + */ + exclude?: string | RegExp | (string | RegExp)[] + /** + * By default, the plugin quits the build process when it encounters an error. If you set this option to true, it will throw a warning instead and leave the code untouched. + * @default false + */ + warnOnError?: boolean +} + +export { rollupVersion } + +/** + * Search up for the nearest workspace root + */ +export declare function searchForWorkspaceRoot(current: string, root?: string): string; + +export declare function send(req: IncomingMessage, res: ServerResponse, content: string | Buffer, type: string, options: SendOptions): void; + +export declare interface SendOptions { + etag?: string; + cacheControl?: string; + headers?: OutgoingHttpHeaders; + map?: SourceMap | null; +} + +export declare type ServerHook = (this: void, server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>; + +export declare interface ServerOptions extends CommonServerOptions { + /** + * Configure HMR-specific options (port, host, path & protocol) + */ + hmr?: HmrOptions | boolean; + /** + * chokidar watch options + * https://github.com/paulmillr/chokidar#api + */ + watch?: WatchOptions; + /** + * Create Vite dev server to be used as a middleware in an existing server + */ + middlewareMode?: boolean | 'html' | 'ssr'; + /** + * Prepend this folder to http requests, for use when proxying vite as a subfolder + * Should start and end with the `/` character + */ + base?: string; + /** + * Options for files served via '/\@fs/'. + */ + fs?: FileSystemServeOptions; + /** + * Origin for the generated asset URLs. + * + * @example `http://127.0.0.1:8080` + */ + origin?: string; + /** + * Pre-transform known direct imports + * @default true + */ + preTransformRequests?: boolean; + /** + * Force dep pre-optimization regardless of whether deps have changed. + * + * @deprecated Use optimizeDeps.force instead, this option may be removed + * in a future minor version without following semver + */ + force?: boolean; +} + +export declare function sortUserPlugins(plugins: (Plugin_2 | Plugin_2[])[] | undefined): [Plugin_2[], Plugin_2[], Plugin_2[]]; + +export declare function splitVendorChunk(options?: { + cache?: SplitVendorChunkCache; +}): GetManualChunk; + +export declare class SplitVendorChunkCache { + cache: Map; + constructor(); + reset(): void; +} + +export declare function splitVendorChunkPlugin(): Plugin_2; + +export declare type SsrDepOptimizationOptions = DepOptimizationConfig; + +export declare type SSRFormat = 'esm' | 'cjs'; + +export declare interface SSROptions { + noExternal?: string | RegExp | (string | RegExp)[] | true; + external?: string[]; + /** + * Define the target for the ssr build. The browser field in package.json + * is ignored for node but used if webworker is the target + * Default: 'node' + */ + target?: SSRTarget; + /** + * Define the format for the ssr build. Since Vite v3 the SSR build generates ESM by default. + * `'cjs'` can be selected to generate a CJS build, but it isn't recommended. This option is + * left marked as experimental to give users more time to update to ESM. CJS builds requires + * complex externalization heuristics that aren't present in the ESM format. + * @experimental + */ + format?: SSRFormat; + /** + * Control over which dependencies are optimized during SSR and esbuild options + * During build: + * no external CJS dependencies are optimized by default + * During dev: + * explicit no external CJS dependencies are optimized by default + * @experimental + */ + optimizeDeps?: SsrDepOptimizationOptions; +} + +export declare type SSRTarget = 'node' | 'webworker'; + +export declare namespace Terser { + export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 + + export interface ParseOptions { + bare_returns?: boolean + /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */ + ecma?: ECMA + html5_comments?: boolean + shebang?: boolean + } + + export interface CompressOptions { + arguments?: boolean + arrows?: boolean + booleans_as_integers?: boolean + booleans?: boolean + collapse_vars?: boolean + comparisons?: boolean + computed_props?: boolean + conditionals?: boolean + dead_code?: boolean + defaults?: boolean + directives?: boolean + drop_console?: boolean + drop_debugger?: boolean + ecma?: ECMA + evaluate?: boolean + expression?: boolean + global_defs?: object + hoist_funs?: boolean + hoist_props?: boolean + hoist_vars?: boolean + ie8?: boolean + if_return?: boolean + inline?: boolean | InlineFunctions + join_vars?: boolean + keep_classnames?: boolean | RegExp + keep_fargs?: boolean + keep_fnames?: boolean | RegExp + keep_infinity?: boolean + loops?: boolean + module?: boolean + negate_iife?: boolean + passes?: number + properties?: boolean + pure_funcs?: string[] + pure_getters?: boolean | 'strict' + reduce_funcs?: boolean + reduce_vars?: boolean + sequences?: boolean | number + side_effects?: boolean + switches?: boolean + toplevel?: boolean + top_retain?: null | string | string[] | RegExp + typeofs?: boolean + unsafe_arrows?: boolean + unsafe?: boolean + unsafe_comps?: boolean + unsafe_Function?: boolean + unsafe_math?: boolean + unsafe_symbols?: boolean + unsafe_methods?: boolean + unsafe_proto?: boolean + unsafe_regexp?: boolean + unsafe_undefined?: boolean + unused?: boolean + } + + export enum InlineFunctions { + Disabled = 0, + SimpleFunctions = 1, + WithArguments = 2, + WithArgumentsAndVariables = 3 + } + + export interface MangleOptions { + eval?: boolean + keep_classnames?: boolean | RegExp + keep_fnames?: boolean | RegExp + module?: boolean + nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler + properties?: boolean | ManglePropertiesOptions + reserved?: string[] + safari10?: boolean + toplevel?: boolean + } + + /** + * An identifier mangler for which the output is invariant with respect to the source code. + */ + export interface SimpleIdentifierMangler { + /** + * Obtains the nth most favored (usually shortest) identifier to rename a variable to. + * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word. + * This function is expected to be stable; Evaluating get(n) === get(n) should always return true. + * @param n - The ordinal of the identifier. + */ + get(n: number): string + } + + /** + * An identifier mangler that leverages character frequency analysis to determine identifier precedence. + */ + export interface WeightedIdentifierMangler extends SimpleIdentifierMangler { + /** + * Modifies the internal weighting of the input characters by the specified delta. + * Will be invoked on the entire printed AST, and then deduct mangleable identifiers. + * @param chars - The characters to modify the weighting of. + * @param delta - The numeric weight to add to the characters. + */ + consider(chars: string, delta: number): number + /** + * Resets character weights. + */ + reset(): void + /** + * Sorts identifiers by character frequency, in preparation for calls to get(n). + */ + sort(): void + } + + export interface ManglePropertiesOptions { + builtins?: boolean + debug?: boolean + keep_quoted?: boolean | 'strict' + nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler + regex?: RegExp | string + reserved?: string[] + } + + export interface FormatOptions { + ascii_only?: boolean + /** @deprecated Not implemented anymore */ + beautify?: boolean + braces?: boolean + comments?: + | boolean + | 'all' + | 'some' + | RegExp + | (( + node: any, + comment: { + value: string + type: 'comment1' | 'comment2' | 'comment3' | 'comment4' + pos: number + line: number + col: number + } + ) => boolean) + ecma?: ECMA + ie8?: boolean + keep_numbers?: boolean + indent_level?: number + indent_start?: number + inline_script?: boolean + keep_quoted_props?: boolean + max_line_len?: number | false + preamble?: string + preserve_annotations?: boolean + quote_keys?: boolean + quote_style?: OutputQuoteStyle + safari10?: boolean + semicolons?: boolean + shebang?: boolean + shorthand?: boolean + source_map?: SourceMapOptions + webkit?: boolean + width?: number + wrap_iife?: boolean + wrap_func_args?: boolean + } + + export enum OutputQuoteStyle { + PreferDouble = 0, + AlwaysSingle = 1, + AlwaysDouble = 2, + AlwaysOriginal = 3 + } + + export interface MinifyOptions { + compress?: boolean | CompressOptions + ecma?: ECMA + enclose?: boolean | string + ie8?: boolean + keep_classnames?: boolean | RegExp + keep_fnames?: boolean | RegExp + mangle?: boolean | MangleOptions + module?: boolean + nameCache?: object + format?: FormatOptions + /** @deprecated deprecated */ + output?: FormatOptions + parse?: ParseOptions + safari10?: boolean + sourceMap?: boolean | SourceMapOptions + toplevel?: boolean + } + + export interface MinifyOutput { + code?: string + map?: object | string + decoded_map?: object | null + } + + export interface SourceMapOptions { + /** Source map object, 'inline' or source map file content */ + content?: object | string + includeSources?: boolean + filename?: string + root?: string + url?: string | 'inline' + } +} + +export declare interface TransformOptions { + ssr?: boolean; + html?: boolean; +} + +export declare interface TransformResult { + code: string; + map: SourceMap | null; + etag?: string; + deps?: string[]; + dynamicDeps?: string[]; +} + +export declare function transformWithEsbuild(code: string, filename: string, options?: EsbuildTransformOptions, inMap?: object): Promise; + +export { Update } + +export { UpdatePayload } + +export declare interface UserConfig { + /** + * Project root directory. Can be an absolute path, or a path relative from + * the location of the config file itself. + * @default process.cwd() + */ + root?: string; + /** + * Base public path when served in development or production. + * @default '/' + */ + base?: string; + /** + * Directory to serve as plain static assets. Files in this directory are + * served and copied to build dist dir as-is without transform. The value + * can be either an absolute file system path or a path relative to project root. + * + * Set to `false` or an empty string to disable copied static assets to build dist dir. + * @default 'public' + */ + publicDir?: string | false; + /** + * Directory to save cache files. Files in this directory are pre-bundled + * deps or some other cache files that generated by vite, which can improve + * the performance. You can use `--force` flag or manually delete the directory + * to regenerate the cache files. The value can be either an absolute file + * system path or a path relative to project root. + * Default to `.vite` when no `package.json` is detected. + * @default 'node_modules/.vite' + */ + cacheDir?: string; + /** + * Explicitly set a mode to run in. This will override the default mode for + * each command, and can be overridden by the command line --mode option. + */ + mode?: string; + /** + * Define global variable replacements. + * Entries will be defined on `window` during dev and replaced during build. + */ + define?: Record; + /** + * Array of vite plugins to use. + */ + plugins?: PluginOption[]; + /** + * Configure resolver + */ + resolve?: ResolveOptions & { + alias?: AliasOptions; + }; + /** + * CSS related options (preprocessors and CSS modules) + */ + css?: CSSOptions; + /** + * JSON loading options + */ + json?: JsonOptions; + /** + * Transform options to pass to esbuild. + * Or set to `false` to disable esbuild. + */ + esbuild?: ESBuildOptions | false; + /** + * Specify additional picomatch patterns to be treated as static assets. + */ + assetsInclude?: string | RegExp | (string | RegExp)[]; + /** + * Server specific options, e.g. host, port, https... + */ + server?: ServerOptions; + /** + * Build specific options + */ + build?: BuildOptions; + /** + * Preview specific options, e.g. host, port, https... + */ + preview?: PreviewOptions; + /** + * Dep optimization options + */ + optimizeDeps?: DepOptimizationOptions; + /** + * SSR specific options + */ + ssr?: SSROptions; + /** + * Experimental features + * + * Features under this field could change in the future and might NOT follow semver. + * Please be careful and always pin Vite's version when using them. + * @experimental + */ + experimental?: ExperimentalOptions; + /** + * Legacy options + * + * Features under this field only follow semver for patches, they could be removed in a + * future minor version. Please always pin Vite's version to a minor when using them. + */ + legacy?: LegacyOptions; + /** + * Log level. + * Default: 'info' + */ + logLevel?: LogLevel; + /** + * Custom logger. + */ + customLogger?: Logger; + /** + * Default: true + */ + clearScreen?: boolean; + /** + * Environment files directory. Can be an absolute path, or a path relative from + * the location of the config file itself. + * @default root + */ + envDir?: string; + /** + * Env variables starts with `envPrefix` will be exposed to your client source code via import.meta.env. + * @default 'VITE_' + */ + envPrefix?: string | string[]; + /** + * Worker bundle options + */ + worker?: { + /** + * Output format for worker bundle + * @default 'iife' + */ + format?: 'es' | 'iife'; + /** + * Vite plugins that apply to worker bundle + */ + plugins?: PluginOption[]; + /** + * Rollup options to build worker bundle + */ + rollupOptions?: Omit; + }; + /** + * Whether your application is a Single Page Application (SPA), + * a Multi-Page Application (MPA), or Custom Application (SSR + * and frameworks with custom HTML handling) + * @default 'spa' + */ + appType?: AppType; +} + +export declare type UserConfigExport = UserConfig | Promise | UserConfigFn; + +export declare type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise; + +export declare const version: string; + +export declare interface ViteDevServer { + /** + * The resolved vite config object + */ + config: ResolvedConfig; + /** + * A connect app instance. + * - Can be used to attach custom middlewares to the dev server. + * - Can also be used as the handler function of a custom http server + * or as a middleware in any connect-style Node.js frameworks + * + * https://github.com/senchalabs/connect#use-middleware + */ + middlewares: Connect.Server; + /** + * native Node http server instance + * will be null in middleware mode + */ + httpServer: http.Server | null; + /** + * chokidar watcher instance + * https://github.com/paulmillr/chokidar#api + */ + watcher: FSWatcher; + /** + * web socket server with `send(payload)` method + */ + ws: WebSocketServer; + /** + * Rollup plugin container that can run plugin hooks on a given file + */ + pluginContainer: PluginContainer; + /** + * Module graph that tracks the import relationships, url to file mapping + * and hmr state. + */ + moduleGraph: ModuleGraph; + /** + * The resolved urls Vite prints on the CLI. null in middleware mode or + * before `server.listen` is called. + */ + resolvedUrls: ResolvedServerUrls | null; + /** + * Programmatically resolve, load and transform a URL and get the result + * without going through the http request pipeline. + */ + transformRequest(url: string, options?: TransformOptions): Promise; + /** + * Apply vite built-in HTML transforms and any plugin HTML transforms. + */ + transformIndexHtml(url: string, html: string, originalUrl?: string): Promise; + /** + * Transform module code into SSR format. + */ + ssrTransform(code: string, inMap: SourceMap | null, url: string, originalCode?: string): Promise; + /** + * Load a given URL as an instantiated module for SSR. + */ + ssrLoadModule(url: string, opts?: { + fixStacktrace?: boolean; + }): Promise>; + /** + * Returns a fixed version of the given stack + */ + ssrRewriteStacktrace(stack: string): string; + /** + * Mutates the given SSR error by rewriting the stacktrace + */ + ssrFixStacktrace(e: Error): void; + /** + * Triggers HMR for a module in the module graph. You can use the `server.moduleGraph` + * API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op. + */ + reloadModule(module: ModuleNode): Promise; + /** + * Start the server. + */ + listen(port?: number, isRestart?: boolean): Promise; + /** + * Stop the server. + */ + close(): Promise; + /** + * Print server urls + */ + printUrls(): void; + /** + * Restart the server. + * + * @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag + */ + restart(forceOptimize?: boolean): Promise; + /* Excluded from this release type: _importGlobMap */ + /* Excluded from this release type: _ssrExternals */ + /* Excluded from this release type: _restartPromise */ + /* Excluded from this release type: _forceOptimizeOnRestart */ + /* Excluded from this release type: _pendingRequests */ + /* Excluded from this release type: _fsDenyGlob */ +} + +export declare 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 +} + +declare class WebSocket_2 extends EventEmitter { + /** The connection is not yet open. */ + static readonly CONNECTING: 0 + /** The connection is open and ready to communicate. */ + static readonly OPEN: 1 + /** The connection is in the process of closing. */ + static readonly CLOSING: 2 + /** The connection is closed. */ + static readonly CLOSED: 3 + + binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments' + readonly bufferedAmount: number + readonly extensions: string + /** Indicates whether the websocket is paused */ + readonly isPaused: boolean + readonly protocol: string + /** The current state of the connection */ + readonly readyState: + | typeof WebSocket_2.CONNECTING + | typeof WebSocket_2.OPEN + | typeof WebSocket_2.CLOSING + | typeof WebSocket_2.CLOSED + readonly url: string + + /** The connection is not yet open. */ + readonly CONNECTING: 0 + /** The connection is open and ready to communicate. */ + readonly OPEN: 1 + /** The connection is in the process of closing. */ + readonly CLOSING: 2 + /** The connection is closed. */ + readonly CLOSED: 3 + + onopen: ((event: WebSocket_2.Event) => void) | null + onerror: ((event: WebSocket_2.ErrorEvent) => void) | null + onclose: ((event: WebSocket_2.CloseEvent) => void) | null + onmessage: ((event: WebSocket_2.MessageEvent) => void) | null + + constructor(address: null) + constructor( + address: string | URL_2, + options?: WebSocket_2.ClientOptions | ClientRequestArgs + ) + constructor( + address: string | URL_2, + protocols?: string | string[], + options?: WebSocket_2.ClientOptions | ClientRequestArgs + ) + + close(code?: number, data?: string | Buffer): void + ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void + pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void + send(data: any, cb?: (err?: Error) => void): void + send( + data: any, + options: { + mask?: boolean | undefined + binary?: boolean | undefined + compress?: boolean | undefined + fin?: boolean | undefined + }, + cb?: (err?: Error) => void + ): void + terminate(): void + + /** + * Pause the websocket causing it to stop emitting events. Some events can still be + * emitted after this is called, until all buffered data is consumed. This method + * is a noop if the ready state is `CONNECTING` or `CLOSED`. + */ + pause(): void + /** + * Make a paused socket resume emitting events. This method is a noop if the ready + * state is `CONNECTING` or `CLOSED`. + */ + resume(): void + + // HTML5 WebSocket events + addEventListener( + method: 'message', + cb: (event: WebSocket_2.MessageEvent) => void, + options?: WebSocket_2.EventListenerOptions + ): void + addEventListener( + method: 'close', + cb: (event: WebSocket_2.CloseEvent) => void, + options?: WebSocket_2.EventListenerOptions + ): void + addEventListener( + method: 'error', + cb: (event: WebSocket_2.ErrorEvent) => void, + options?: WebSocket_2.EventListenerOptions + ): void + addEventListener( + method: 'open', + cb: (event: WebSocket_2.Event) => void, + options?: WebSocket_2.EventListenerOptions + ): void + + removeEventListener( + method: 'message', + cb: (event: WebSocket_2.MessageEvent) => void + ): void + removeEventListener( + method: 'close', + cb: (event: WebSocket_2.CloseEvent) => void + ): void + removeEventListener( + method: 'error', + cb: (event: WebSocket_2.ErrorEvent) => void + ): void + removeEventListener( + method: 'open', + cb: (event: WebSocket_2.Event) => void + ): void + + // Events + on( + event: 'close', + listener: (this: WebSocket_2, code: number, reason: Buffer) => void + ): this + on(event: 'error', listener: (this: WebSocket_2, err: Error) => void): this + on( + event: 'upgrade', + listener: (this: WebSocket_2, request: IncomingMessage) => void + ): this + on( + event: 'message', + listener: ( + this: WebSocket_2, + data: WebSocket_2.RawData, + isBinary: boolean + ) => void + ): this + on(event: 'open', listener: (this: WebSocket_2) => void): this + on( + event: 'ping' | 'pong', + listener: (this: WebSocket_2, data: Buffer) => void + ): this + on( + event: 'unexpected-response', + listener: ( + this: WebSocket_2, + request: ClientRequest, + response: IncomingMessage + ) => void + ): this + on( + event: string | symbol, + listener: (this: WebSocket_2, ...args: any[]) => void + ): this + + once( + event: 'close', + listener: (this: WebSocket_2, code: number, reason: Buffer) => void + ): this + once(event: 'error', listener: (this: WebSocket_2, err: Error) => void): this + once( + event: 'upgrade', + listener: (this: WebSocket_2, request: IncomingMessage) => void + ): this + once( + event: 'message', + listener: ( + this: WebSocket_2, + data: WebSocket_2.RawData, + isBinary: boolean + ) => void + ): this + once(event: 'open', listener: (this: WebSocket_2) => void): this + once( + event: 'ping' | 'pong', + listener: (this: WebSocket_2, data: Buffer) => void + ): this + once( + event: 'unexpected-response', + listener: ( + this: WebSocket_2, + request: ClientRequest, + response: IncomingMessage + ) => void + ): this + once( + event: string | symbol, + listener: (this: WebSocket_2, ...args: any[]) => void + ): this + + off( + event: 'close', + listener: (this: WebSocket_2, code: number, reason: Buffer) => void + ): this + off(event: 'error', listener: (this: WebSocket_2, err: Error) => void): this + off( + event: 'upgrade', + listener: (this: WebSocket_2, request: IncomingMessage) => void + ): this + off( + event: 'message', + listener: ( + this: WebSocket_2, + data: WebSocket_2.RawData, + isBinary: boolean + ) => void + ): this + off(event: 'open', listener: (this: WebSocket_2) => void): this + off( + event: 'ping' | 'pong', + listener: (this: WebSocket_2, data: Buffer) => void + ): this + off( + event: 'unexpected-response', + listener: ( + this: WebSocket_2, + request: ClientRequest, + response: IncomingMessage + ) => void + ): this + off( + event: string | symbol, + listener: (this: WebSocket_2, ...args: any[]) => void + ): this + + addListener( + event: 'close', + listener: (code: number, reason: Buffer) => void + ): this + addListener(event: 'error', listener: (err: Error) => void): this + addListener( + event: 'upgrade', + listener: (request: IncomingMessage) => void + ): this + addListener( + event: 'message', + listener: (data: WebSocket_2.RawData, isBinary: boolean) => void + ): this + addListener(event: 'open', listener: () => void): this + addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this + addListener( + event: 'unexpected-response', + listener: (request: ClientRequest, response: IncomingMessage) => void + ): this + addListener(event: string | symbol, listener: (...args: any[]) => void): this + + removeListener( + event: 'close', + listener: (code: number, reason: Buffer) => void + ): this + removeListener(event: 'error', listener: (err: Error) => void): this + removeListener( + event: 'upgrade', + listener: (request: IncomingMessage) => void + ): this + removeListener( + event: 'message', + listener: (data: WebSocket_2.RawData, isBinary: boolean) => void + ): this + removeListener(event: 'open', listener: () => void): this + removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this + removeListener( + event: 'unexpected-response', + listener: (request: ClientRequest, response: IncomingMessage) => void + ): this + removeListener( + event: string | symbol, + listener: (...args: any[]) => void + ): this +} + +declare namespace WebSocket_2 { + /** + * Data represents the raw message payload received over the WebSocket. + */ + type RawData = Buffer | ArrayBuffer | Buffer[] + + /** + * Data represents the message payload received over the WebSocket. + */ + type Data = string | Buffer | ArrayBuffer | Buffer[] + + /** + * CertMeta represents the accepted types for certificate & key data. + */ + type CertMeta = string | string[] | Buffer | Buffer[] + + /** + * VerifyClientCallbackSync is a synchronous callback used to inspect the + * incoming message. The return value (boolean) of the function determines + * whether or not to accept the handshake. + */ + type VerifyClientCallbackSync = (info: { + origin: string + secure: boolean + req: IncomingMessage + }) => boolean + + /** + * VerifyClientCallbackAsync is an asynchronous callback used to inspect the + * incoming message. The return value (boolean) of the function determines + * whether or not to accept the handshake. + */ + type VerifyClientCallbackAsync = ( + info: { origin: string; secure: boolean; req: IncomingMessage }, + callback: ( + res: boolean, + code?: number, + message?: string, + headers?: OutgoingHttpHeaders + ) => void + ) => void + + interface ClientOptions extends SecureContextOptions { + protocol?: string | undefined + followRedirects?: boolean | undefined + generateMask?(mask: Buffer): void + handshakeTimeout?: number | undefined + maxRedirects?: number | undefined + perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined + localAddress?: string | undefined + protocolVersion?: number | undefined + headers?: { [key: string]: string } | undefined + origin?: string | undefined + agent?: Agent | undefined + host?: string | undefined + family?: number | undefined + checkServerIdentity?(servername: string, cert: CertMeta): boolean + rejectUnauthorized?: boolean | undefined + maxPayload?: number | undefined + skipUTF8Validation?: boolean | undefined + } + + interface PerMessageDeflateOptions { + serverNoContextTakeover?: boolean | undefined + clientNoContextTakeover?: boolean | undefined + serverMaxWindowBits?: number | undefined + clientMaxWindowBits?: number | undefined + zlibDeflateOptions?: + | { + flush?: number | undefined + finishFlush?: number | undefined + chunkSize?: number | undefined + windowBits?: number | undefined + level?: number | undefined + memLevel?: number | undefined + strategy?: number | undefined + dictionary?: Buffer | Buffer[] | DataView | undefined + info?: boolean | undefined + } + | undefined + zlibInflateOptions?: ZlibOptions | undefined + threshold?: number | undefined + concurrencyLimit?: number | undefined + } + + interface Event { + type: string + target: WebSocket + } + + interface ErrorEvent { + error: any + message: string + type: string + target: WebSocket + } + + interface CloseEvent { + wasClean: boolean + code: number + reason: string + type: string + target: WebSocket + } + + interface MessageEvent { + data: Data + type: string + target: WebSocket + } + + interface EventListenerOptions { + once?: boolean | undefined + } + + interface ServerOptions { + host?: string | undefined + port?: number | undefined + backlog?: number | undefined + server?: Server | Server_2 | undefined + verifyClient?: + | VerifyClientCallbackAsync + | VerifyClientCallbackSync + | undefined + handleProtocols?: ( + protocols: Set, + request: IncomingMessage + ) => string | false + path?: string | undefined + noServer?: boolean | undefined + clientTracking?: boolean | undefined + perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined + maxPayload?: number | undefined + skipUTF8Validation?: boolean | undefined + WebSocket?: typeof WebSocket.WebSocket | undefined + } + + interface AddressInfo { + address: string + family: string + port: number + } + + // WebSocket Server + class Server extends EventEmitter { + options: ServerOptions + path: string + clients: Set + + constructor(options?: ServerOptions, callback?: () => void) + + address(): AddressInfo | string + close(cb?: (err?: Error) => void): void + handleUpgrade( + request: IncomingMessage, + socket: Duplex, + upgradeHead: Buffer, + callback: (client: T, request: IncomingMessage) => void + ): void + shouldHandle(request: IncomingMessage): boolean | Promise + + // Events + on( + event: 'connection', + cb: (this: Server, socket: T, request: IncomingMessage) => void + ): this + on(event: 'error', cb: (this: Server, error: Error) => void): this + on( + event: 'headers', + cb: (this: Server, headers: string[], request: IncomingMessage) => void + ): this + on(event: 'close' | 'listening', cb: (this: Server) => void): this + on( + event: string | symbol, + listener: (this: Server, ...args: any[]) => void + ): this + + once( + event: 'connection', + cb: (this: Server, socket: T, request: IncomingMessage) => void + ): this + once(event: 'error', cb: (this: Server, error: Error) => void): this + once( + event: 'headers', + cb: (this: Server, headers: string[], request: IncomingMessage) => void + ): this + once(event: 'close' | 'listening', cb: (this: Server) => void): this + once( + event: string | symbol, + listener: (this: Server, ...args: any[]) => void + ): this + + off( + event: 'connection', + cb: (this: Server, socket: T, request: IncomingMessage) => void + ): this + off(event: 'error', cb: (this: Server, error: Error) => void): this + off( + event: 'headers', + cb: (this: Server, headers: string[], request: IncomingMessage) => void + ): this + off(event: 'close' | 'listening', cb: (this: Server) => void): this + off( + event: string | symbol, + listener: (this: Server, ...args: any[]) => void + ): this + + addListener( + event: 'connection', + cb: (client: T, request: IncomingMessage) => void + ): this + addListener(event: 'error', cb: (err: Error) => void): this + addListener( + event: 'headers', + cb: (headers: string[], request: IncomingMessage) => void + ): this + addListener(event: 'close' | 'listening', cb: () => void): this + addListener( + event: string | symbol, + listener: (...args: any[]) => void + ): this + + removeListener(event: 'connection', cb: (client: T) => void): this + removeListener(event: 'error', cb: (err: Error) => void): this + removeListener( + event: 'headers', + cb: (headers: string[], request: IncomingMessage) => void + ): this + removeListener(event: 'close' | 'listening', cb: () => void): this + removeListener( + event: string | symbol, + listener: (...args: any[]) => void + ): this + } + + const WebSocketServer: typeof Server + interface WebSocketServer extends Server {} // tslint:disable-line no-empty-interface + const WebSocket: typeof WebSocketAlias + interface WebSocket extends WebSocketAlias {} // tslint:disable-line no-empty-interface + + // WebSocket stream + function createWebSocketStream( + websocket: WebSocket, + options?: DuplexOptions + ): Duplex +} +export { WebSocket_2 as WebSocket } + +export declare const WebSocketAlias: typeof WebSocket_2; + +export declare interface WebSocketAlias extends WebSocket_2 {} + +export declare interface WebSocketClient { + /** + * Send event to the client + */ + send(payload: HMRPayload): void; + /** + * Send custom event + */ + send(event: string, payload?: CustomPayload['data']): void; + /** + * The raw WebSocket instance + * @advanced + */ + socket: WebSocket_2; +} + +export declare type WebSocketCustomListener = (data: T, client: WebSocketClient) => void; + +export declare interface WebSocketServer { + /** + * Get all connected clients. + */ + clients: Set; + /** + * Broadcast events to all clients + */ + send(payload: HMRPayload): void; + /** + * Send custom event + */ + send(event: T, payload?: InferCustomEventPayload): void; + /** + * Disconnect all clients and terminate the server. + */ + close(): Promise; + /** + * Handle custom event emitted by `import.meta.hot.send` + */ + on: WebSocket_2.Server['on'] & { + (event: T, listener: WebSocketCustomListener>): void; + }; + /** + * Unregister event listener. + */ + off: WebSocket_2.Server['off'] & { + (event: string, listener: Function): void; + }; +} + +export { } diff --git a/node_modules/vite/dist/node/index.js b/node_modules/vite/dist/node/index.js new file mode 100644 index 0000000..5ea6d88 --- /dev/null +++ b/node_modules/vite/dist/node/index.js @@ -0,0 +1,146 @@ +export { b as build, q as createFilter, v as createLogger, c as createServer, e as defineConfig, f as formatPostcssSourceMap, i as getDepOptimizationConfig, j as isDepsOptimizerEnabled, l as loadConfigFromFile, x as loadEnv, k as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, h as resolveBaseUrl, g as resolveConfig, y as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, w as searchForWorkspaceRoot, u as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-5605cfa4.js'; +export { VERSION as version } from './constants.js'; +export { version as esbuildVersion } from 'esbuild'; +export { VERSION as rollupVersion } from 'rollup'; +import 'node:fs'; +import 'node:path'; +import 'node:url'; +import 'node:perf_hooks'; +import 'node:module'; +import 'tty'; +import 'path'; +import 'fs'; +import 'events'; +import 'assert'; +import 'util'; +import 'net'; +import 'url'; +import 'http'; +import 'stream'; +import 'os'; +import 'child_process'; +import 'node:os'; +import 'node:crypto'; +import 'node:util'; +import 'node:dns'; +import 'resolve'; +import 'crypto'; +import 'node:buffer'; +import 'module'; +import 'worker_threads'; +import 'zlib'; +import 'https'; +import 'tls'; +import 'node:http'; +import 'node:https'; +import 'querystring'; +import 'node:readline'; +import 'node:child_process'; +import 'node:zlib'; + +// This file will be built for both ESM and CJS. Avoid relying on other modules as possible. +const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`; +const cssLangRE = new RegExp(cssLangs); +const isCSSRequest = (request) => cssLangRE.test(request); +// Use splitVendorChunkPlugin() to get the same manualChunks strategy as Vite 2.7 +// We don't recommend using this strategy as a general solution moving forward +// splitVendorChunk is a simple index/vendor strategy that was used in Vite +// until v2.8. It is exposed to let people continue to use it in case it was +// working well for their setups. +// The cache needs to be reset on buildStart for watch mode to work correctly +// Don't use this manualChunks strategy for ssr, lib mode, and 'umd' or 'iife' +class SplitVendorChunkCache { + constructor() { + this.cache = new Map(); + } + reset() { + this.cache = new Map(); + } +} +function splitVendorChunk(options = {}) { + const cache = options.cache ?? new SplitVendorChunkCache(); + return (id, { getModuleInfo }) => { + if (id.includes('node_modules') && + !isCSSRequest(id) && + staticImportedByEntry(id, getModuleInfo, cache.cache)) { + return 'vendor'; + } + }; +} +function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) { + if (cache.has(id)) { + return cache.get(id); + } + if (importStack.includes(id)) { + // circular deps! + cache.set(id, false); + return false; + } + const mod = getModuleInfo(id); + if (!mod) { + cache.set(id, false); + return false; + } + if (mod.isEntry) { + cache.set(id, true); + return true; + } + const someImporterIs = mod.importers.some((importer) => staticImportedByEntry(importer, getModuleInfo, cache, importStack.concat(id))); + cache.set(id, someImporterIs); + return someImporterIs; +} +function splitVendorChunkPlugin() { + const caches = []; + function createSplitVendorChunk(output, config) { + const cache = new SplitVendorChunkCache(); + caches.push(cache); + const build = config.build ?? {}; + const format = output?.format; + if (!build.ssr && !build.lib && format !== 'umd' && format !== 'iife') { + return splitVendorChunk({ cache }); + } + } + return { + name: 'vite:split-vendor-chunk', + config(config) { + let outputs = config?.build?.rollupOptions?.output; + if (outputs) { + outputs = Array.isArray(outputs) ? outputs : [outputs]; + for (const output of outputs) { + const viteManualChunks = createSplitVendorChunk(output, config); + if (viteManualChunks) { + if (output.manualChunks) { + if (typeof output.manualChunks === 'function') { + const userManualChunks = output.manualChunks; + output.manualChunks = (id, api) => { + return userManualChunks(id, api) ?? viteManualChunks(id, api); + }; + } + // else, leave the object form of manualChunks untouched, as + // we can't safely replicate rollup handling. + } + else { + output.manualChunks = viteManualChunks; + } + } + } + } + else { + return { + build: { + rollupOptions: { + output: { + manualChunks: createSplitVendorChunk({}, config) + } + } + } + }; + } + }, + buildStart() { + caches.forEach((cache) => cache.reset()); + } + }; +} + +export { splitVendorChunk, splitVendorChunkPlugin }; diff --git a/node_modules/vite/index.cjs b/node_modules/vite/index.cjs new file mode 100644 index 0000000..525b1b7 --- /dev/null +++ b/node_modules/vite/index.cjs @@ -0,0 +1,34 @@ +/* eslint-disable no-restricted-globals */ + +// type utils +module.exports.defineConfig = (config) => config + +// proxy cjs utils (sync functions) +Object.assign(module.exports, require('./dist/node-cjs/publicUtils.cjs')) + +// async functions, can be redirect from ESM build +const asyncFunctions = [ + 'build', + 'createServer', + 'preview', + 'transformWithEsbuild', + 'resolveConfig', + 'optimizeDeps', + 'formatPostcssSourceMap', + 'loadConfigFromFile', + 'preprocessCSS' +] +asyncFunctions.forEach((name) => { + module.exports[name] = (...args) => + import('./dist/node/index.js').then((i) => i[name](...args)) +}) + +// some sync functions are marked not supported due to their complexity and uncommon usage +const unsupportedCJS = ['resolvePackageEntry', 'resolvePackageData'] +unsupportedCJS.forEach((name) => { + module.exports[name] = () => { + throw new Error( + `"${name}" is not supported in CJS build of Vite 3.\nPlease use ESM or dynamic imports \`const { ${name} } = await import('vite')\`.` + ) + } +}) diff --git a/node_modules/vite/package.json b/node_modules/vite/package.json new file mode 100644 index 0000000..3f3c159 --- /dev/null +++ b/node_modules/vite/package.json @@ -0,0 +1,154 @@ +{ + "name": "vite", + "version": "3.2.5", + "type": "module", + "license": "MIT", + "author": "Evan You", + "description": "Native-ESM powered web dev build tool", + "bin": { + "vite": "bin/vite.js" + }, + "main": "./dist/node/index.js", + "module": "./dist/node/index.js", + "types": "./dist/node/index.d.ts", + "exports": { + ".": { + "types": "./dist/node/index.d.ts", + "import": "./dist/node/index.js", + "require": "./index.cjs" + }, + "./client": { + "types": "./client.d.ts" + }, + "./dist/client/*": "./dist/client/*", + "./package.json": "./package.json" + }, + "files": [ + "bin", + "dist", + "client.d.ts", + "index.cjs", + "types" + ], + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/vitejs/vite.git", + "directory": "packages/vite" + }, + "bugs": { + "url": "https://github.com/vitejs/vite/issues" + }, + "homepage": "https://github.com/vitejs/vite/tree/main/#readme", + "scripts": { + "dev": "rimraf dist && pnpm run build-bundle -w", + "build": "rimraf dist && run-s build-bundle build-types", + "build-bundle": "rollup --config rollup.config.ts --configPlugin typescript", + "build-types": "run-s build-types-temp build-types-pre-patch build-types-roll build-types-post-patch build-types-check", + "build-types-temp": "tsc --emitDeclarationOnly --outDir temp/node -p src/node", + "build-types-pre-patch": "tsx scripts/prePatchTypes.ts", + "build-types-roll": "api-extractor run && rimraf temp", + "build-types-post-patch": "tsx scripts/postPatchTypes.ts", + "build-types-check": "tsc --project tsconfig.check.json", + "lint": "eslint --cache --ext .ts src/**", + "format": "prettier --write --cache --parser typescript \"src/**/*.ts\"", + "prepublishOnly": "npm run build" + }, + "//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!", + "dependencies": { + "esbuild": "^0.15.9", + "postcss": "^8.4.18", + "resolve": "^1.22.1", + "rollup": "^2.79.1" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "devDependencies": { + "@ampproject/remapping": "^2.2.0", + "@babel/parser": "^7.20.0", + "@babel/types": "^7.20.0", + "@jridgewell/trace-mapping": "^0.3.17", + "@rollup/plugin-alias": "^4.0.2", + "@rollup/plugin-commonjs": "^23.0.2", + "@rollup/plugin-dynamic-import-vars": "^2.0.1", + "@rollup/plugin-json": "^4.1.0", + "@rollup/plugin-node-resolve": "14.1.0", + "@rollup/plugin-typescript": "^8.5.0", + "@rollup/pluginutils": "^4.2.1", + "acorn": "^8.8.1", + "acorn-walk": "^8.2.0", + "cac": "^6.7.14", + "chokidar": "^3.5.3", + "connect": "^3.7.0", + "connect-history-api-fallback": "^2.0.0", + "convert-source-map": "^1.9.0", + "cors": "^2.8.5", + "cross-spawn": "^7.0.3", + "debug": "^4.3.4", + "dep-types": "link:./src/types", + "dotenv": "^14.3.2", + "dotenv-expand": "^5.1.0", + "es-module-lexer": "^1.1.0", + "estree-walker": "^3.0.1", + "etag": "^1.8.1", + "fast-glob": "^3.2.12", + "http-proxy": "^1.18.1", + "json5": "^2.2.1", + "launch-editor-middleware": "^2.6.0", + "magic-string": "^0.26.7", + "micromatch": "^4.0.5", + "mlly": "^0.5.16", + "mrmime": "^1.0.1", + "okie": "^1.0.1", + "open": "^8.4.0", + "parse5": "^7.1.1", + "periscopic": "^3.0.4", + "picocolors": "^1.0.0", + "picomatch": "^2.3.1", + "postcss-import": "^15.0.0", + "postcss-load-config": "^4.0.1", + "postcss-modules": "^6.0.0", + "resolve.exports": "^1.1.0", + "sirv": "^2.0.2", + "source-map-js": "^1.0.2", + "source-map-support": "^0.5.21", + "strip-ansi": "^7.0.1", + "strip-literal": "^0.4.2", + "tsconfck": "^2.0.1", + "tslib": "^2.4.0", + "types": "link:./types", + "ufo": "^0.8.6", + "ws": "^8.10.0" + }, + "peerDependencies": { + "@types/node": ">= 14", + "less": "*", + "sass": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "sass": { + "optional": true + }, + "stylus": { + "optional": true + }, + "less": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } +} diff --git a/node_modules/vite/types/alias.d.ts b/node_modules/vite/types/alias.d.ts new file mode 100644 index 0000000..91f7363 --- /dev/null +++ b/node_modules/vite/types/alias.d.ts @@ -0,0 +1,6 @@ +export type { + Alias, + ResolverFunction, + ResolverObject, + AliasOptions +} from '../dist/node' diff --git a/node_modules/vite/types/anymatch.d.ts b/node_modules/vite/types/anymatch.d.ts new file mode 100644 index 0000000..c98e950 --- /dev/null +++ b/node_modules/vite/types/anymatch.d.ts @@ -0,0 +1 @@ +export type { AnymatchFn, AnymatchPattern, Matcher } from '../dist/node' diff --git a/node_modules/vite/types/chokidar.d.ts b/node_modules/vite/types/chokidar.d.ts new file mode 100644 index 0000000..eae2209 --- /dev/null +++ b/node_modules/vite/types/chokidar.d.ts @@ -0,0 +1,11 @@ +export type { + FSWatcher, + WatchOptions, + AwaitWriteFinishOptions +} from '../dist/node' + +import type { FSWatcher, WatchOptions } from '../dist/node' +export function watch( + paths: string | ReadonlyArray, + options?: WatchOptions +): FSWatcher diff --git a/node_modules/vite/types/commonjs.d.ts b/node_modules/vite/types/commonjs.d.ts new file mode 100644 index 0000000..8b95405 --- /dev/null +++ b/node_modules/vite/types/commonjs.d.ts @@ -0,0 +1 @@ +export type { RollupCommonJSOptions } from '../dist/node' diff --git a/node_modules/vite/types/connect.d.ts b/node_modules/vite/types/connect.d.ts new file mode 100644 index 0000000..5050255 --- /dev/null +++ b/node_modules/vite/types/connect.d.ts @@ -0,0 +1 @@ +export type { Connect } from '../dist/node' diff --git a/node_modules/vite/types/customEvent.d.ts b/node_modules/vite/types/customEvent.d.ts new file mode 100644 index 0000000..64d0c19 --- /dev/null +++ b/node_modules/vite/types/customEvent.d.ts @@ -0,0 +1,22 @@ +import type { + ErrorPayload, + FullReloadPayload, + PrunePayload, + UpdatePayload +} from './hmrPayload' + +export interface CustomEventMap { + 'vite:beforeUpdate': UpdatePayload + 'vite:afterUpdate': UpdatePayload + 'vite:beforePrune': PrunePayload + 'vite:beforeFullReload': FullReloadPayload + 'vite:error': ErrorPayload + 'vite:invalidate': InvalidatePayload +} + +export interface InvalidatePayload { + path: string +} + +export type InferCustomEventPayload = + T extends keyof CustomEventMap ? CustomEventMap[T] : any diff --git a/node_modules/vite/types/dynamicImportVars.d.ts b/node_modules/vite/types/dynamicImportVars.d.ts new file mode 100644 index 0000000..2d46aaf --- /dev/null +++ b/node_modules/vite/types/dynamicImportVars.d.ts @@ -0,0 +1 @@ +export type { RollupDynamicImportVarsOptions } from '../dist/node' diff --git a/node_modules/vite/types/hmrPayload.d.ts b/node_modules/vite/types/hmrPayload.d.ts new file mode 100644 index 0000000..8390950 --- /dev/null +++ b/node_modules/vite/types/hmrPayload.d.ts @@ -0,0 +1,61 @@ +export type HMRPayload = + | ConnectedPayload + | UpdatePayload + | FullReloadPayload + | CustomPayload + | ErrorPayload + | PrunePayload + +export interface ConnectedPayload { + type: 'connected' +} + +export interface UpdatePayload { + type: 'update' + updates: Update[] +} + +export interface Update { + type: 'js-update' | 'css-update' + path: string + acceptedPath: string + timestamp: number + /** + * @experimental internal + */ + explicitImportRequired?: boolean | undefined +} + +export interface PrunePayload { + type: 'prune' + paths: string[] +} + +export interface FullReloadPayload { + type: 'full-reload' + path?: string +} + +export interface CustomPayload { + type: 'custom' + event: string + data?: any +} + +export interface ErrorPayload { + type: 'error' + err: { + [name: string]: any + message: string + stack: string + id?: string + frame?: string + plugin?: string + pluginCode?: string + loc?: { + file?: string + line: number + column: number + } + } +} diff --git a/node_modules/vite/types/hot.d.ts b/node_modules/vite/types/hot.d.ts new file mode 100644 index 0000000..985f3a4 --- /dev/null +++ b/node_modules/vite/types/hot.d.ts @@ -0,0 +1,33 @@ +import type { InferCustomEventPayload } from './customEvent' + +export type ModuleNamespace = Record & { + [Symbol.toStringTag]: 'Module' +} + +export interface ViteHotContext { + readonly data: any + + accept(): void + accept(cb: (mod: ModuleNamespace | undefined) => void): void + accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void + accept( + deps: readonly string[], + cb: (mods: Array) => void + ): void + + acceptExports(exportNames: string | readonly string[]): void + acceptExports( + exportNames: string | readonly string[], + cb: (mod: ModuleNamespace | undefined) => void + ): void + + dispose(cb: (data: any) => void): void + decline(): void + invalidate(): void + + on( + event: T, + cb: (payload: InferCustomEventPayload) => void + ): void + send(event: T, data?: InferCustomEventPayload): void +} diff --git a/node_modules/vite/types/http-proxy.d.ts b/node_modules/vite/types/http-proxy.d.ts new file mode 100644 index 0000000..54bbefc --- /dev/null +++ b/node_modules/vite/types/http-proxy.d.ts @@ -0,0 +1 @@ +export type { HttpProxy } from '../dist/node' diff --git a/node_modules/vite/types/importGlob.d.ts b/node_modules/vite/types/importGlob.d.ts new file mode 100644 index 0000000..321e380 --- /dev/null +++ b/node_modules/vite/types/importGlob.d.ts @@ -0,0 +1,97 @@ +export interface ImportGlobOptions< + Eager extends boolean, + AsType extends string +> { + /** + * Import type for the import url. + */ + as?: AsType + /** + * Import as static or dynamic + * + * @default false + */ + eager?: Eager + /** + * Import only the specific named export. Set to `default` to import the default export. + */ + import?: string + /** + * Custom queries + */ + query?: string | Record + /** + * Search files also inside `node_modules/` and hidden directories (e.g. `.git/`). This might have impact on performance. + * + * @default false + */ + exhaustive?: boolean +} + +export type GeneralImportGlobOptions = ImportGlobOptions + +export interface KnownAsTypeMap { + raw: string + url: string + worker: Worker +} + +export interface ImportGlobFunction { + /** + * Import a list of files with a glob pattern. + * + * Overload 1: No generic provided, infer the type from `eager` and `as` + */ + < + Eager extends boolean, + As extends string, + T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown + >( + glob: string | string[], + options?: ImportGlobOptions + ): (Eager extends true ? true : false) extends true + ? Record + : Record Promise> + /** + * Import a list of files with a glob pattern. + * + * Overload 2: Module generic provided, infer the type from `eager: false` + */ + ( + glob: string | string[], + options?: ImportGlobOptions + ): Record Promise> + /** + * Import a list of files with a glob pattern. + * + * Overload 3: Module generic provided, infer the type from `eager: true` + */ + ( + glob: string | string[], + options: ImportGlobOptions + ): Record +} + +export interface ImportGlobEagerFunction { + /** + * Eagerly import a list of files with a glob pattern. + * + * Overload 1: No generic provided, infer the type from `as` + */ + < + As extends string, + T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown + >( + glob: string | string[], + options?: Omit, 'eager'> + ): Record + /** + * Eagerly import a list of files with a glob pattern. + * + * Overload 2: Module generic provided + */ + ( + glob: string | string[], + options?: Omit, 'eager'> + ): Record +} diff --git a/node_modules/vite/types/importMeta.d.ts b/node_modules/vite/types/importMeta.d.ts new file mode 100644 index 0000000..da338b6 --- /dev/null +++ b/node_modules/vite/types/importMeta.d.ts @@ -0,0 +1,28 @@ +// This file is an augmentation to the built-in ImportMeta interface +// Thus cannot contain any top-level imports +// + +/* eslint-disable @typescript-eslint/consistent-type-imports */ + +interface ImportMetaEnv { + [key: string]: any + BASE_URL: string + MODE: string + DEV: boolean + PROD: boolean + SSR: boolean +} + +interface ImportMeta { + url: string + + readonly hot?: import('./hot').ViteHotContext + + readonly env: ImportMetaEnv + + glob: import('./importGlob').ImportGlobFunction + /** + * @deprecated Use `import.meta.glob('*', { eager: true })` instead + */ + globEager: import('./importGlob').ImportGlobEagerFunction +} diff --git a/node_modules/vite/types/package.json b/node_modules/vite/types/package.json new file mode 100644 index 0000000..5757150 --- /dev/null +++ b/node_modules/vite/types/package.json @@ -0,0 +1,3 @@ +{ + "//": "this file is here to make typescript happy when moduleResolution=node16+" +} diff --git a/node_modules/vite/types/terser.d.ts b/node_modules/vite/types/terser.d.ts new file mode 100644 index 0000000..695795d --- /dev/null +++ b/node_modules/vite/types/terser.d.ts @@ -0,0 +1 @@ +export type { Terser } from '../dist/node' diff --git a/node_modules/vite/types/ws.d.ts b/node_modules/vite/types/ws.d.ts new file mode 100644 index 0000000..3916212 --- /dev/null +++ b/node_modules/vite/types/ws.d.ts @@ -0,0 +1 @@ +export type { WebSocket, WebSocketAlias } from '../dist/node' diff --git a/node_modules/vitest/LICENSE.md b/node_modules/vitest/LICENSE.md new file mode 100644 index 0000000..0cb365b --- /dev/null +++ b/node_modules/vitest/LICENSE.md @@ -0,0 +1,2175 @@ +# Vitest core license +Vitest is released under the MIT license: + +MIT License + +Copyright (c) 2021-Present Anthony Fu +Copyright (c) 2021-Present Matias Capeletto + +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. + +# Licenses of bundled dependencies +The published Vitest artifact additionally contains code with the following licenses: +Apache-2.0, BSD-3-Clause, ISC, MIT + +# Bundled dependencies: +## @antfu/install-pkg +License: MIT +By: Anthony Fu +Repository: git+https://github.com/antfu/install-pkg.git + +> MIT License +> +> Copyright (c) 2021 Anthony Fu +> +> 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. + +--------------------------------------- + +## @jridgewell/sourcemap-codec +License: MIT +By: Rich Harris +Repository: git+https://github.com/jridgewell/sourcemap-codec.git + +> 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. + +--------------------------------------- + +## @nodelib/fs.scandir +License: MIT +Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.scandir + +> The MIT License (MIT) +> +> Copyright (c) Denis Malinochkin +> +> 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. + +--------------------------------------- + +## @nodelib/fs.stat +License: MIT +Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.stat + +> The MIT License (MIT) +> +> Copyright (c) Denis Malinochkin +> +> 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. + +--------------------------------------- + +## @nodelib/fs.walk +License: MIT +Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.walk + +> The MIT License (MIT) +> +> Copyright (c) Denis Malinochkin +> +> 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. + +--------------------------------------- + +## @sinonjs/commons +License: BSD-3-Clause +Repository: git+https://github.com/sinonjs/commons.git + +> BSD 3-Clause License +> +> Copyright (c) 2018, Sinon.JS +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without +> modification, are permitted provided that the following conditions are met: +> +> * Redistributions of source code must retain the above copyright notice, this +> list of conditions and the following disclaimer. +> +> * 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. +> +> * 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. + +--------------------------------------- + +## @sinonjs/fake-timers +License: BSD-3-Clause +By: Christian Johansen +Repository: https://github.com/sinonjs/fake-timers.git + +> Copyright (c) 2010-2014, Christian Johansen, christian@cjohansen.no. 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. + +--------------------------------------- + +## ansi-escapes +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/ansi-escapes + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## ansi-regex +License: MIT +By: Sindre Sorhus +Repository: chalk/ansi-regex + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## ansi-styles +License: MIT +By: Sindre Sorhus +Repository: chalk/ansi-styles + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## birpc +License: MIT +By: Anthony Fu +Repository: git+https://github.com/antfu/birpc.git + +> MIT License +> +> Copyright (c) 2021 Anthony Fu +> +> 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. + +--------------------------------------- + +## braces +License: MIT +By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm +Repository: micromatch/braces + +> The MIT License (MIT) +> +> Copyright (c) 2014-2018, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## chai-subset +License: MIT +By: Andrii Shumada, Robert Herhold +Repository: https://github.com/debitoor/chai-subset.git + +> The MIT License (MIT) +> +> Copyright (c) 2014 +> +> 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. + +--------------------------------------- + +## cli-cursor +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/cli-cursor + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## cli-truncate +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/cli-truncate + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## cross-spawn +License: MIT +By: André Cruz +Repository: git@github.com:moxystudio/node-cross-spawn.git + +> The MIT License (MIT) +> +> Copyright (c) 2018 Made With MOXY Lda +> +> 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 +License: BSD-3-Clause +Repository: git://github.com/kpdecker/jsdiff.git + +> Software License Agreement (BSD License) +> +> Copyright (c) 2009-2015, Kevin Decker +> +> All rights reserved. +> +> Redistribution and use of this software in source and binary forms, with or without modification, +> are permitted provided that the following conditions are met: +> +> * Redistributions of source code must retain the above +> copyright notice, this list of conditions and the +> following disclaimer. +> +> * 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. +> +> * Neither the name of Kevin Decker 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 OWNER 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. + +--------------------------------------- + +## eastasianwidth +License: MIT +By: Masaki Komagata +Repository: git://github.com/komagata/eastasianwidth.git + +--------------------------------------- + +## emoji-regex +License: MIT +By: Mathias Bynens +Repository: https://github.com/mathiasbynens/emoji-regex.git + +> Copyright Mathias Bynens +> +> 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. + +--------------------------------------- + +## event-target-polyfill +License: MIT +By: Ben Lesh +Repository: git+https://github.com/benlesh/event-target-polyfill.git + +> MIT License +> +> Copyright (c) 2020 Ben Lesh +> +> 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. + +--------------------------------------- + +## execa +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/execa + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## expect-type +License: Apache-2.0 +Repository: https://github.com/mmkal/expect-type.git + +> 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. + +--------------------------------------- + +## fast-glob +License: MIT +By: Denis Malinochkin +Repository: mrmlnc/fast-glob + +> The MIT License (MIT) +> +> Copyright (c) Denis Malinochkin +> +> 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. + +--------------------------------------- + +## fastq +License: ISC +By: Matteo Collina +Repository: git+https://github.com/mcollina/fastq.git + +> Copyright (c) 2015-2020, Matteo Collina +> +> 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. + +--------------------------------------- + +## fill-range +License: MIT +By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling +Repository: jonschlinkert/fill-range + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## find-up +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/find-up + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## flatted +License: ISC +By: Andrea Giammarchi +Repository: git+https://github.com/WebReflection/flatted.git + +> ISC License +> +> Copyright (c) 2018-2020, Andrea Giammarchi, @WebReflection +> +> 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. + +--------------------------------------- + +## get-stream +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/get-stream + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## get-tsconfig +License: MIT +By: Hiroki Osame +Repository: privatenumber/get-tsconfig + +> MIT License +> +> Copyright (c) Hiroki Osame +> +> 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. + +--------------------------------------- + +## glob-parent +License: ISC +By: Gulp Team, Elan Shanker, Blaine Bublitz +Repository: gulpjs/glob-parent + +> The ISC License +> +> Copyright (c) 2015, 2019 Elan Shanker +> +> 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. + +--------------------------------------- + +## human-signals +License: Apache-2.0 +By: ehmicky +Repository: ehmicky/human-signals + +> 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 2021 ehmicky +> +> 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. + +--------------------------------------- + +## is-extglob +License: MIT +By: Jon Schlinkert +Repository: jonschlinkert/is-extglob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2016, Jon Schlinkert +> +> 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. + +--------------------------------------- + +## is-fullwidth-code-point +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-fullwidth-code-point + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## is-glob +License: MIT +By: Jon Schlinkert, Brian Woodward, Daniel Perez +Repository: micromatch/is-glob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2017, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## is-number +License: MIT +By: Jon Schlinkert, Olsten Larck, Rouven Weßling +Repository: jonschlinkert/is-number + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## is-stream +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-stream + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## isexe +License: ISC +By: Isaac Z. Schlueter +Repository: git+https://github.com/isaacs/isexe.git + +> 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. + +--------------------------------------- + +## kleur +License: MIT +By: Luke Edwards +Repository: lukeed/kleur + +> The MIT License (MIT) +> +> Copyright (c) Luke Edwards (lukeed.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. + +--------------------------------------- + +## locate-path +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/locate-path + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## log-update +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/log-update + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## magic-string +License: MIT +By: Rich Harris +Repository: https://github.com/rich-harris/magic-string + +> Copyright 2018 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. + +--------------------------------------- + +## merge-stream +License: MIT +By: Stephen Sugden +Repository: grncdr/merge-stream + +> The MIT License (MIT) +> +> Copyright (c) Stephen Sugden (stephensugden.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. + +--------------------------------------- + +## merge2 +License: MIT +Repository: git@github.com:teambition/merge2.git + +> The MIT License (MIT) +> +> Copyright (c) 2014-2020 Teambition +> +> 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. + +--------------------------------------- + +## micromatch +License: MIT +By: Jon Schlinkert, Amila Welihinda, Bogdan Chadkin, Brian Woodward, Devon Govett, Elan Shanker, Fabrício Matté, Martin Kolárik, Olsten Larck, Paul Miller, Tom Byrer, Tyler Akins, Peter Bright, Kuba Juszczyk +Repository: micromatch/micromatch + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## mimic-fn +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/mimic-fn + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## mlly +License: MIT +Repository: unjs/mlly + +> MIT License +> +> Copyright (c) Pooya Parsa +> +> 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. + +--------------------------------------- + +## natural-compare +License: MIT +By: Lauri Rooden +Repository: git://github.com/litejs/natural-compare-lite.git + +--------------------------------------- + +## npm-run-path +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/npm-run-path + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## onetime +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/onetime + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## p-limit +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/p-limit + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## p-locate +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/p-locate + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## path-exists +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/path-exists + +> 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. + +--------------------------------------- + +## path-key +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/path-key + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## pathe +License: MIT +Repository: unjs/pathe + +> MIT License +> +> Copyright (c) 2021 UnJS +> +> 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. +> +> -------------------------------------------------------------------------------- +> +> 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. + +--------------------------------------- + +## picomatch +License: MIT +By: Jon Schlinkert +Repository: micromatch/picomatch + +> The MIT License (MIT) +> +> Copyright (c) 2017-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## pretty-format +License: MIT +By: James Kyle +Repository: https://github.com/facebook/jest.git + +> MIT License +> +> Copyright (c) Facebook, Inc. and its affiliates. +> +> 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. + +--------------------------------------- + +## prompts +License: MIT +By: Terkel Gjervig +Repository: terkelg/prompts + +> MIT License +> +> Copyright (c) 2018 Terkel Gjervig Nielsen +> +> 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. + +--------------------------------------- + +## queue-microtask +License: MIT +By: Feross Aboukhadijeh +Repository: git://github.com/feross/queue-microtask.git + +> The MIT License (MIT) +> +> 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 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. + +--------------------------------------- + +## react-is +License: MIT +Repository: https://github.com/facebook/react.git + +> MIT License +> +> Copyright (c) Facebook, Inc. and its affiliates. +> +> 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. + +--------------------------------------- + +## restore-cursor +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/restore-cursor + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## reusify +License: MIT +By: Matteo Collina +Repository: git+https://github.com/mcollina/reusify.git + +> The MIT License (MIT) +> +> Copyright (c) 2015 Matteo Collina +> +> 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. + +--------------------------------------- + +## run-parallel +License: MIT +By: Feross Aboukhadijeh +Repository: git://github.com/feross/run-parallel.git + +> The MIT License (MIT) +> +> 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 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. + +--------------------------------------- + +## shebang-command +License: MIT +By: Kevin Mårtensson +Repository: kevva/shebang-command + +> MIT License +> +> Copyright (c) Kevin Mårtensson (github.com/kevva) +> +> 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. + +--------------------------------------- + +## shebang-regex +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/shebang-regex + +> 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. + +--------------------------------------- + +## signal-exit +License: ISC +By: Ben Coe +Repository: https://github.com/tapjs/signal-exit.git + +> The ISC License +> +> Copyright (c) 2015, 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. + +--------------------------------------- + +## sisteransi +License: MIT +By: Terkel Gjervig +Repository: https://github.com/terkelg/sisteransi + +> MIT License +> +> Copyright (c) 2018 Terkel Gjervig Nielsen +> +> 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. + +--------------------------------------- + +## slice-ansi +License: MIT +Repository: chalk/slice-ansi + +> MIT License +> +> Copyright (c) DC +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## string-width +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/string-width + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## strip-ansi +License: MIT +By: Sindre Sorhus +Repository: chalk/strip-ansi + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## strip-final-newline +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/strip-final-newline + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## to-regex-range +License: MIT +By: Jon Schlinkert, Rouven Weßling +Repository: micromatch/to-regex-range + +> The MIT License (MIT) +> +> Copyright (c) 2015-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## type-detect +License: MIT +By: Jake Luer, Keith Cirkel, David Losert, Aleksey Shvayka, Lucas Fernandes da Costa, Grant Snodgrass, Jeremy Tice, Edward Betts, dvlsg, Amila Welihinda, Jake Champion, Miroslav Bajtoš +Repository: git+ssh://git@github.com/chaijs/type-detect.git + +> Copyright (c) 2013 Jake Luer (http://alogicalparadox.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. + +--------------------------------------- + +## which +License: ISC +By: Isaac Z. Schlueter +Repository: git://github.com/isaacs/node-which.git + +> 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. + +--------------------------------------- + +## wrap-ansi +License: MIT +By: Sindre Sorhus +Repository: chalk/wrap-ansi + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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. + +--------------------------------------- + +## ws +License: MIT +By: Einar Otto Stangvik +Repository: websockets/ws + +> Copyright (c) 2011 Einar Otto Stangvik +> +> 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. + +--------------------------------------- + +## yocto-queue +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/yocto-queue + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://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/vitest/README.md b/node_modules/vitest/README.md new file mode 100644 index 0000000..1708d4b --- /dev/null +++ b/node_modules/vitest/README.md @@ -0,0 +1,7 @@ +# vitest + +[![NPM version](https://img.shields.io/npm/v/vitest?color=a1b858&label=)](https://www.npmjs.com/package/vitest) + +A blazing fast unit test framework powered by Vite. + +[GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/) diff --git a/node_modules/vitest/browser.d.ts b/node_modules/vitest/browser.d.ts new file mode 100644 index 0000000..174e295 --- /dev/null +++ b/node_modules/vitest/browser.d.ts @@ -0,0 +1 @@ +export * from './dist/browser' diff --git a/node_modules/vitest/config.d.ts b/node_modules/vitest/config.d.ts new file mode 100644 index 0000000..a11119b --- /dev/null +++ b/node_modules/vitest/config.d.ts @@ -0,0 +1 @@ +export * from './dist/config.js' diff --git a/node_modules/vitest/dist/browser.d.ts b/node_modules/vitest/dist/browser.d.ts new file mode 100644 index 0000000..6c54cee --- /dev/null +++ b/node_modules/vitest/dist/browser.d.ts @@ -0,0 +1,20 @@ +export { A as AssertType, E as EnhancedSpy, q as ExpectTypeOf, x as Mock, y as MockContext, w as MockInstance, z as Mocked, B as MockedClass, u as MockedFunction, v as MockedObject, S as SpyInstance, j as afterAll, l as afterEach, r as assertType, h as beforeAll, k as beforeEach, n as createExpect, e as describe, m as expect, p as expectTypeOf, i as it, o as onTestFailed, d as suite, t as test } from './index-2d10c3fd.js'; +import { b as ResolvedConfig } from './types-e1e1d1e5.js'; +export { a1 as AfterSuiteRunMeta, A as ApiConfig, a7 as ArgumentsType, a6 as Arrayable, a4 as Awaitable, ao as BaseCoverageOptions, au as BenchFunction, as as Benchmark, av as BenchmarkAPI, at as BenchmarkResult, ar as BenchmarkUserOptions, B as BuiltinEnvironment, j as CSSModuleScopeStrategy, C as CollectLineNumbers, g as CollectLines, ab as Constructable, i as Context, aq as CoverageC8Options, ap as CoverageIstanbulOptions, am as CoverageOptions, aj as CoverageProvider, ak as CoverageProviderModule, al as CoverageReporter, a9 as DeepMerge, D as DoneCallback, ae as Environment, E as EnvironmentOptions, ad as EnvironmentReturn, ah as ErrorWithDiff, a as File, x as HookCleanupCallback, H as HookListener, I as InlineConfig, J as JSDOMOptions, a8 as MergeInsertions, ac as ModuleCache, c as ModuleGraphData, aa as MutableArray, a5 as Nullable, ai as OnServerRestartHandler, O as OnTestFailedHandler, ag as ParsedStack, e as RawErrsMap, d as Reporter, a0 as ResolveIdFunction, b as ResolvedConfig, an as ResolvedCoverageOptions, h as RootAndTarget, m as RunMode, R as RuntimeConfig, K as RuntimeContext, S as SequenceHooks, P as SnapshotData, X as SnapshotMatchOptions, Y as SnapshotResult, W as SnapshotStateOptions, _ as SnapshotSummary, Q as SnapshotUpdateState, q as Suite, w as SuiteAPI, z as SuiteCollector, G as SuiteFactory, y as SuiteHooks, s as Task, o as TaskBase, p as TaskResult, T as TaskResultPack, n as TaskState, r as Test, v as TestAPI, L as TestContext, t as TestFunction, u as TestOptions, f as TscErrorInfo, l as TypecheckConfig, Z as UncheckedSnapshot, U as UserConfig, af as UserConsoleLog, N as Vitest, V as VitestEnvironment, k as VitestRunMode, $ as WorkerContext, a3 as WorkerGlobalState, a2 as WorkerRPC } from './types-e1e1d1e5.js'; +import * as chai from 'chai'; +export { chai }; +export { assert, should } from 'chai'; +export { Bench as BenchFactory, Options as BenchOptions, Task as BenchTask, TaskResult as BenchTaskResult } from 'tinybench'; +import 'tinyspy'; +import 'vite'; +import 'vite-node/client'; +import 'vite-node/server'; +import 'vite-node'; +import 'node:fs'; +import 'node:worker_threads'; + +declare function startTests(paths: string[], config: ResolvedConfig): Promise; + +declare function setupGlobalEnv(config: ResolvedConfig): Promise; + +export { setupGlobalEnv, startTests }; diff --git a/node_modules/vitest/dist/browser.js b/node_modules/vitest/dist/browser.js new file mode 100644 index 0000000..31e2863 --- /dev/null +++ b/node_modules/vitest/dist/browser.js @@ -0,0 +1,34 @@ +export { c as createExpect, d as describe, e as expect, i as it, s as suite, t as test } from './chunk-runtime-chain.6df5a66b.js'; +import { e as dist } from './chunk-utils-import.2baa69a9.js'; +export { a as afterAll, d as afterEach, f as assertType, b as beforeAll, c as beforeEach, o as onTestFailed } from './chunk-utils-import.2baa69a9.js'; +export { a as setupGlobalEnv, s as startTests } from './chunk-runtime-setup.731b2b04.js'; +import * as chai from 'chai'; +export { chai }; +export { assert, should } from 'chai'; +import 'util'; +import './chunk-mock-date.a1c85759.js'; +import 'node:path'; +import 'picocolors'; +import 'local-pkg'; +import './chunk-utils-env.b861e3a0.js'; +import 'node:url'; +import 'path'; +import './vendor-_commonjsHelpers.addc3445.js'; +import './chunk-utils-timers.52534f96.js'; +import './vendor-index.723a074f.js'; +import 'tinyspy'; +import './chunk-utils-source-map.60562959.js'; +import './chunk-runtime-rpc.7f83c8a9.js'; +import 'node:fs'; +import 'fs'; +import 'perf_hooks'; +import './chunk-integrations-coverage.44413252.js'; +import './chunk-runtime-error.fad2c32b.js'; +import 'vite-node/source-map'; +import './chunk-env-node.b3664da2.js'; +import 'node:console'; + + + +var expectTypeOf = dist.expectTypeOf; +export { expectTypeOf }; diff --git a/node_modules/vitest/dist/chunk-api-setup.16ac28c0.js b/node_modules/vitest/dist/chunk-api-setup.16ac28c0.js new file mode 100644 index 0000000..ca9941f --- /dev/null +++ b/node_modules/vitest/dist/chunk-api-setup.16ac28c0.js @@ -0,0 +1,4589 @@ +import { promises } from 'node:fs'; +import { c as createBirpc } from './vendor-index.783e7f3e.js'; +import require$$0$1 from 'stream'; +import require$$0 from 'zlib'; +import require$$3 from 'net'; +import require$$4 from 'tls'; +import require$$5 from 'crypto'; +import require$$2 from 'events'; +import require$$1 from 'https'; +import require$$2$1 from 'http'; +import require$$7 from 'url'; +import { A as API_PATH } from './chunk-utils-env.b861e3a0.js'; +import './chunk-mock-date.a1c85759.js'; +import { b as parseStacktrace } from './chunk-utils-source-map.60562959.js'; +import 'node:url'; +import 'path'; +import 'node:path'; +import 'picocolors'; +import 'local-pkg'; +import './chunk-utils-timers.52534f96.js'; + +async function getModuleGraph(ctx, id) { + const graph = {}; + const externalized = /* @__PURE__ */ new Set(); + const inlined = /* @__PURE__ */ new Set(); + function clearId(id2) { + return (id2 == null ? void 0 : id2.replace(/\?v=\w+$/, "")) || ""; + } + async function get(mod, seen = /* @__PURE__ */ new Map()) { + if (!mod || !mod.id) + return; + if (seen.has(mod)) + return seen.get(mod); + let id2 = clearId(mod.id); + seen.set(mod, id2); + const rewrote = await ctx.vitenode.shouldExternalize(id2); + if (rewrote) { + id2 = rewrote; + externalized.add(id2); + seen.set(mod, id2); + } else { + inlined.add(id2); + } + const mods = Array.from(mod.importedModules).filter((i) => i.id && !i.id.includes("/vitest/dist/")); + graph[id2] = (await Promise.all(mods.map((m) => get(m, seen)))).filter(Boolean); + return id2; + } + await get(ctx.server.moduleGraph.getModuleById(id)); + return { + graph, + externalized: Array.from(externalized), + inlined: Array.from(inlined) + }; +} + +/*! (c) 2020 Andrea Giammarchi */ + +const {parse: $parse, stringify: $stringify} = JSON; +const {keys} = Object; + +const Primitive = String; // it could be Number +const primitive = 'string'; // it could be 'number' + +const ignore = {}; +const object = 'object'; + +const noop = (_, value) => value; + +const primitives = value => ( + value instanceof Primitive ? Primitive(value) : value +); + +const Primitives = (_, value) => ( + typeof value === primitive ? new Primitive(value) : value +); + +const revive = (input, parsed, output, $) => { + const lazy = []; + for (let ke = keys(output), {length} = ke, y = 0; y < length; y++) { + const k = ke[y]; + const value = output[k]; + if (value instanceof Primitive) { + const tmp = input[value]; + if (typeof tmp === object && !parsed.has(tmp)) { + parsed.add(tmp); + output[k] = ignore; + lazy.push({k, a: [input, parsed, tmp, $]}); + } + else + output[k] = $.call(output, k, tmp); + } + else if (output[k] !== ignore) + output[k] = $.call(output, k, value); + } + for (let {length} = lazy, i = 0; i < length; i++) { + const {k, a} = lazy[i]; + output[k] = $.call(output, k, revive.apply(null, a)); + } + return output; +}; + +const set = (known, input, value) => { + const index = Primitive(input.push(value) - 1); + known.set(value, index); + return index; +}; + +const parse$3 = (text, reviver) => { + const input = $parse(text, Primitives).map(primitives); + const value = input[0]; + const $ = reviver || noop; + const tmp = typeof value === object && value ? + revive(input, new Set, value, $) : + value; + return $.call({'': tmp}, '', tmp); +}; + +const stringify = (value, replacer, space) => { + const $ = replacer && typeof replacer === object ? + (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) : + (replacer || noop); + const known = new Map; + const input = []; + const output = []; + let i = +set(known, input, $.call({'': value}, '', value)); + let firstRun = !i; + while (i < input.length) { + firstRun = true; + output[i] = $stringify(input[i++], replace, space); + } + return '[' + output.join(',') + ']'; + function replace(key, value) { + if (firstRun) { + firstRun = !firstRun; + return value; + } + const after = $.call(this, key, value); + switch (typeof after) { + case object: + if (after === null) return after; + case primitive: + return known.get(after) || set(known, input, after); + } + return after; + } +}; + +var bufferUtil$1 = {exports: {}}; + +var constants = { + BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; + +var unmask$1; +var mask; + +const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat$1(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER$3; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) return target.slice(0, offset); + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer$1(buf) { + if (buf.byteLength === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer$2(data) { + toBuffer$2.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer$2.readOnly = false; + } + + return buf; +} + +bufferUtil$1.exports = { + concat: concat$1, + mask: _mask, + toArrayBuffer: toArrayBuffer$1, + toBuffer: toBuffer$2, + unmask: _unmask +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require('bufferutil'); + + mask = bufferUtil$1.exports.mask = function (source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + + unmask$1 = bufferUtil$1.exports.unmask = function (buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + // Continue regardless of the error. + } +} + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter$1 { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +var limiter = Limiter$1; + +const zlib = require$$0; + +const bufferUtil = bufferUtil$1.exports; +const Limiter = limiter; +const { kStatusCode: kStatusCode$2 } = constants; + +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError$1 = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate$4 { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError$1]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) data = data.slice(0, data.length - 4); + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +var permessageDeflate = PerMessageDeflate$4; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError$1] = new RangeError('Max payload size exceeded'); + this[kError$1].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError$1][kStatusCode$2] = 1009; + this.removeListener('data', inflateOnData); + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + err[kStatusCode$2] = 1007; + this[kCallback](err); +} + +var validation = {exports: {}}; + +var isValidUTF8_1; + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars$2 = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode$2(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +validation.exports = { + isValidStatusCode: isValidStatusCode$2, + isValidUTF8: _isValidUTF8, + tokenChars: tokenChars$2 +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require('utf-8-validate'); + + isValidUTF8_1 = validation.exports.isValidUTF8 = function (buf) { + return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + // Continue regardless of the error. + } +} + +const { Writable } = require$$0$1; + +const PerMessageDeflate$3 = permessageDeflate; +const { + BINARY_TYPES: BINARY_TYPES$1, + EMPTY_BUFFER: EMPTY_BUFFER$2, + kStatusCode: kStatusCode$1, + kWebSocket: kWebSocket$2 +} = constants; +const { concat, toArrayBuffer, unmask } = bufferUtil$1.exports; +const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validation.exports; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver$1 extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._binaryType = options.binaryType || BINARY_TYPES$1[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket$2] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._state = GET_INFO; + this._loop = false; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = buf.slice(n); + return buf.slice(0, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = buf.slice(n); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + let err; + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + err = this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + err = this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + err = this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + err = this.getData(cb); + break; + default: + // `INFLATING` + this._loop = false; + return; + } + } while (this._loop); + + cb(err); + } + + /** + * Reads the first two bytes of a frame. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getInfo() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + this._loop = false; + return error( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if (!this._fragmented) { + this._loop = false; + return error( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + this._loop = false; + return error( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + } + + if (compressed) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if (this._payloadLength > 0x7d) { + this._loop = false; + return error( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + } + } else { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + this._loop = false; + return error( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + } + } else if (this._masked) { + this._loop = false; + return error( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else return this.haveLength(); + } + + /** + * Gets extended payload length (7+16). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength16() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + return this.haveLength(); + } + + /** + * Gets extended payload length (7+64). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength64() { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + this._loop = false; + return error( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + return this.haveLength(); + } + + /** + * Payload length has been read. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + haveLength() { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + this._loop = false; + return error( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER$2; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + + if ( + this._masked && + (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 + ) { + unmask(data, this._mask); + } + } + + if (this._opcode > 0x07) return this.controlMessage(data); + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + return this.dataMessage(); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + return cb( + error( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ) + ); + } + + this._fragments.push(buf); + } + + const er = this.dataMessage(); + if (er) return cb(er); + + this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @return {(Error|undefined)} A possible error + * @private + */ + dataMessage() { + if (this._fin) { + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else { + data = fragments; + } + + this.emit('message', data, true); + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + this._loop = false; + return error( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('message', buf, false); + } + } + + this._state = GET_INFO; + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data) { + if (this._opcode === 0x08) { + this._loop = false; + + if (data.length === 0) { + this.emit('conclude', 1005, EMPTY_BUFFER$2); + this.end(); + } else if (data.length === 1) { + return error( + RangeError, + 'invalid payload length 1', + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode$1(code)) { + return error( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + } + + const buf = data.slice(2); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + return error( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('conclude', code, buf); + this.end(); + } + } else if (this._opcode === 0x09) { + this.emit('ping', data); + } else { + this.emit('pong', data); + } + + this._state = GET_INFO; + } +} + +var receiver = Receiver$1; + +/** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ +function error(ErrorCtor, message, prefix, statusCode, errorCode) { + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, error); + err.code = errorCode; + err[kStatusCode$1] = statusCode; + return err; +} + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */ +const { randomFillSync } = require$$5; + +const PerMessageDeflate$2 = permessageDeflate; +const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants; +const { isValidStatusCode } = validation.exports; +const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtil$1.exports; + +const kByteLength = Symbol('kByteLength'); +const maskBuffer = Buffer.alloc(4); + +/** + * HyBi Sender implementation. + */ +class Sender$1 { + /** + * Creates a Sender instance. + * + * @param {(net.Socket|tls.Socket)} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + + if (options.generateMask) { + options.generateMask(mask); + } else { + randomFillSync(mask, 0, 4); + } + + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + + let dataLength; + + if (typeof data === 'string') { + if ( + (!options.mask || skipMasking) && + options[kByteLength] !== undefined + ) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + + let payloadLength = dataLength; + + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + + if (!options.mask) return [target, data]; + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (skipMasking) return [target, data]; + + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER$1; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x08, + readOnly: false, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender$1.frame(buf, options), cb); + } + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer$1(data); + byteLength = data.length; + readOnly = toBuffer$1.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x09, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender$1.frame(data, options), cb); + } + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer$1(data); + byteLength = data.length; + readOnly = toBuffer$1.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x0a, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender$1.frame(data, options), cb); + } + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer$1(data); + byteLength = data.length; + readOnly = toBuffer$1.readOnly; + } + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + if (perMessageDeflate) { + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } else { + this.sendFrame( + Sender$1.frame(data, { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1: false + }), + cb + ); + } + } + + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender$1.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName]; + + this._bufferedBytes += options[kByteLength]; + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < this._queue.length; i++) { + const params = this._queue[i]; + const callback = params[params.length - 1]; + + if (typeof callback === 'function') callback(err); + } + + return; + } + + this._bufferedBytes -= options[kByteLength]; + this._deflating = false; + options.readOnly = false; + this.sendFrame(Sender$1.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +var sender = Sender$1; + +const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants; + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +} + +Object.defineProperty(Event.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if ( + !options[kForOnEventAttribute$1] && + listener[kListener$1] === handler && + !listener[kForOnEventAttribute$1] + ) { + return; + } + } + + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event('open'); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1]; + wrapper[kListener$1] = handler; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +var eventTarget = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent +}; + +/** + * Call an event listener + * + * @param {(Function|Object)} listener The listener to call + * @param {*} thisArg The value to use as `this`` when calling the listener + * @param {Event} event The event to pass to the listener + * @private + */ +function callListener(listener, thisArg, event) { + if (typeof listener === 'object' && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } +} + +const { tokenChars: tokenChars$1 } = validation.exports; + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse$2(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars$1[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars$1[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars$1[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars$1[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars$1[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format$1(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +var extension$1 = { format: format$1, parse: parse$2 }; + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Readable$" }] */ + +const EventEmitter$1 = require$$2; +const https = require$$1; +const http$1 = require$$2$1; +const net = require$$3; +const tls = require$$4; +const { randomBytes, createHash: createHash$1 } = require$$5; +const { URL: URL$1 } = require$$7; + +const PerMessageDeflate$1 = permessageDeflate; +const Receiver = receiver; +const Sender = sender; +const { + BINARY_TYPES, + EMPTY_BUFFER, + GUID: GUID$1, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket: kWebSocket$1, + NOOP +} = constants; +const { + EventTarget: { addEventListener, removeEventListener } +} = eventTarget; +const { format, parse: parse$1 } = extension$1; +const { toBuffer } = bufferUtil$1.exports; + +const closeTimeout = 30 * 1000; +const kAborted = Symbol('kAborted'); +const protocolVersions = [8, 13]; +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket$1 extends EventEmitter$1 { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._extensions = {}; + this._paused = false; + this._protocol = ''; + this._readyState = WebSocket$1.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._isServer = true; + } + } + + /** + * This deviates from the WHATWG interface since ws doesn't support the + * required default "blob" type (instead we define a custom "nodebuffer" + * type). + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + this._sender = new Sender(socket, this._extensions, options.generateMask); + this._receiver = receiver; + this._socket = socket; + + receiver[kWebSocket$1] = this; + socket[kWebSocket$1] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + socket.setTimeout(0); + socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError$1); + + this._readyState = WebSocket$1.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket$1.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate$1.extensionName]) { + this._extensions[PerMessageDeflate$1.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket$1.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket$1.CLOSED) return; + if (this.readyState === WebSocket$1.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + return abortHandshake$1(this, this._req, msg); + } + + if (this.readyState === WebSocket$1.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket$1.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + // + // Specify a timeout for the closing handshake to complete. + // + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket$1.CONNECTING || + this.readyState === WebSocket$1.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket$1.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket$1.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket$1.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket$1.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket$1.CONNECTING || + this.readyState === WebSocket$1.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket$1.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket$1.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate$1.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket$1.CLOSED) return; + if (this.readyState === WebSocket$1.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + return abortHandshake$1(this, this._req, msg); + } + + if (this._socket) { + this._readyState = WebSocket$1.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$1, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$1.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$1, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$1.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$1, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$1.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$1, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$1.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket$1.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket$1.prototype.addEventListener = addEventListener; +WebSocket$1.prototype.removeEventListener = removeEventListener; + +var websocket = WebSocket$1; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + createConnection: undefined, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL$1) { + parsedUrl = address; + websocket._url = address.href; + } else { + try { + parsedUrl = new URL$1(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + + websocket._url = address; + } + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https.request : http$1.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = isSecure ? tlsConnect : netConnect; + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate$1( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake$1(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake$1(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL$1(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake$1( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket$1.CONNECTING) return; + + req = websocket._req = null; + + if (res.headers.upgrade.toLowerCase() !== 'websocket') { + abortHandshake$1(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash$1('sha1') + .update(key + GUID$1) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake$1(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake$1(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse$1(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake$1(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate$1.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake$1(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake$1(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate$1.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + req.end(); +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket$1.CLOSING; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake$1(websocket, stream, message) { + websocket._readyState = WebSocket$1.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake$1); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + cb(err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket$1]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket$1] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket$1]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket$1]; + + if (websocket._socket[kWebSocket$1] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + websocket.emit('error', err); +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket$1].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket$1].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket$1]; + + websocket.pong(data, !websocket._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket$1].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The listener of the `net.Socket` `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket$1]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket$1.CLOSING; + + let chunk; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written and `readable.read()` + // will return `null`. If instead, the socket is paused, any possible buffered + // data will be read as a single chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + (chunk = websocket._socket.read()) !== null + ) { + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket$1] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the `net.Socket` `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket$1]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the `net.Socket` `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket$1]; + + websocket._readyState = WebSocket$1.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the `net.Socket` `'error'` event. + * + * @private + */ +function socketOnError$1() { + const websocket = this[kWebSocket$1]; + + this.removeListener('error', socketOnError$1); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket$1.CLOSING; + this.destroy(); + } +} + +const { tokenChars } = validation.exports; + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +var subprotocol$1 = { parse }; + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */ + +const EventEmitter = require$$2; +const http = require$$2$1; +const { createHash } = require$$5; + +const extension = extension$1; +const PerMessageDeflate = permessageDeflate; +const subprotocol = subprotocol$1; +const WebSocket = websocket; +const { GUID, kWebSocket } = constants; + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = req.headers['sec-websocket-key']; + const version = +req.headers['sec-websocket-version']; + + if (req.method !== 'GET') { + const message = 'Invalid HTTP method'; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + + if (req.headers.upgrade.toLowerCase() !== 'websocket') { + const message = 'Invalid Upgrade header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!key || !keyRegex.test(key)) { + const message = 'Missing or invalid Sec-WebSocket-Key header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (version !== 8 && version !== 13) { + const message = 'Missing or invalid Sec-WebSocket-Version header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Protocol header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = + 'Invalid or unacceptable Sec-WebSocket-Extensions header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new this.options.WebSocket(null); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +var websocketServer = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + // + // The socket is writable unless the user destroyed or ended it before calling + // `server.handleUpgrade()` or in the `verifyClient` function, which is a user + // error. Handling this does not make much sense as the worst that can happen + // is that some of the data written by the user might be discarded due to the + // call to `socket.end()` below, which triggers an `'error'` event that in + // turn causes the socket to be destroyed. + // + message = message || http.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.once('finish', socket.destroy); + + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); +} + +/** + * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least + * one listener for it, otherwise call `abortHandshake()`. + * + * @param {WebSocketServer} server The WebSocket server + * @param {http.IncomingMessage} req The request object + * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} message The HTTP response body + * @private + */ +function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { + if (server.listenerCount('wsClientError')) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + + server.emit('wsClientError', err, socket, req); + } else { + abortHandshake(socket, code, message); + } +} + +function setup(ctx) { + var _a; + const wss = new websocketServer({ noServer: true }); + const clients = /* @__PURE__ */ new Map(); + (_a = ctx.server.httpServer) == null ? void 0 : _a.on("upgrade", (request, socket, head) => { + if (!request.url) + return; + const { pathname } = new URL(request.url, "http://localhost"); + if (pathname !== API_PATH) + return; + wss.handleUpgrade(request, socket, head, (ws) => { + wss.emit("connection", ws, request); + setupClient(ws); + }); + }); + function setupClient(ws) { + const rpc = createBirpc( + { + async onWatcherStart() { + await ctx.report("onWatcherStart"); + }, + async onFinished() { + await ctx.report("onFinished"); + }, + async onCollected(files) { + ctx.state.collectFiles(files); + await ctx.report("onCollected", files); + }, + async onTaskUpdate(packs) { + ctx.state.updateTasks(packs); + await ctx.report("onTaskUpdate", packs); + }, + getFiles() { + return ctx.state.getFiles(); + }, + async getPaths() { + return await ctx.state.getPaths(); + }, + readFile(id) { + return promises.readFile(id, "utf-8"); + }, + writeFile(id, content) { + return promises.writeFile(id, content, "utf-8"); + }, + async rerun(files) { + await ctx.rerunFiles(files); + }, + getConfig() { + return ctx.config; + }, + async getTransformResult(id) { + const result = await ctx.vitenode.transformRequest(id); + if (result) { + try { + result.source = result.source || await promises.readFile(id, "utf-8"); + } catch { + } + return result; + } + }, + async getModuleGraph(id) { + return getModuleGraph(ctx, id); + }, + updateSnapshot(file) { + if (!file) + return ctx.updateSnapshot(); + return ctx.updateSnapshot([file.filepath]); + } + }, + { + post: (msg) => ws.send(msg), + on: (fn) => ws.on("message", fn), + eventNames: ["onUserConsoleLog", "onFinished", "onCollected"], + serialize: stringify, + deserialize: parse$3 + } + ); + clients.set(ws, rpc); + ws.on("close", () => { + clients.delete(ws); + }); + } + ctx.reporters.push(new WebSocketReporter(ctx, wss, clients)); +} +class WebSocketReporter { + constructor(ctx, wss, clients) { + this.ctx = ctx; + this.wss = wss; + this.clients = clients; + } + onCollected(files) { + if (this.clients.size === 0) + return; + this.clients.forEach((client) => { + var _a; + (_a = client.onCollected) == null ? void 0 : _a.call(client, files); + }); + } + async onTaskUpdate(packs) { + if (this.clients.size === 0) + return; + packs.forEach(([, result]) => { + var _a; + if (result == null ? void 0 : result.error) + result.error.stacks = parseStacktrace(result.error); + (_a = result == null ? void 0 : result.errors) == null ? void 0 : _a.forEach((error) => { + error.stacks = parseStacktrace(error); + }); + }); + this.clients.forEach((client) => { + var _a; + (_a = client.onTaskUpdate) == null ? void 0 : _a.call(client, packs); + }); + } + onFinished(files) { + this.clients.forEach((client) => { + var _a; + (_a = client.onFinished) == null ? void 0 : _a.call(client, files); + }); + } + onUserConsoleLog(log) { + this.clients.forEach((client) => { + var _a; + (_a = client.onUserConsoleLog) == null ? void 0 : _a.call(client, log); + }); + } +} + +export { setup }; diff --git a/node_modules/vitest/dist/chunk-env-node.b3664da2.js b/node_modules/vitest/dist/chunk-env-node.b3664da2.js new file mode 100644 index 0000000..49d9e69 --- /dev/null +++ b/node_modules/vitest/dist/chunk-env-node.b3664da2.js @@ -0,0 +1,401 @@ +import { Console } from 'node:console'; +import { importModule } from 'local-pkg'; + +var node = { + name: "node", + async setup(global) { + global.console.Console = Console; + return { + teardown(global2) { + delete global2.console.Console; + } + }; + } +}; + +const LIVING_KEYS = [ + "DOMException", + "URL", + "URLSearchParams", + "EventTarget", + "NamedNodeMap", + "Node", + "Attr", + "Element", + "DocumentFragment", + "DOMImplementation", + "Document", + "XMLDocument", + "CharacterData", + "Text", + "CDATASection", + "ProcessingInstruction", + "Comment", + "DocumentType", + "NodeList", + "RadioNodeList", + "HTMLCollection", + "HTMLOptionsCollection", + "DOMStringMap", + "DOMTokenList", + "StyleSheetList", + "HTMLElement", + "HTMLHeadElement", + "HTMLTitleElement", + "HTMLBaseElement", + "HTMLLinkElement", + "HTMLMetaElement", + "HTMLStyleElement", + "HTMLBodyElement", + "HTMLHeadingElement", + "HTMLParagraphElement", + "HTMLHRElement", + "HTMLPreElement", + "HTMLUListElement", + "HTMLOListElement", + "HTMLLIElement", + "HTMLMenuElement", + "HTMLDListElement", + "HTMLDivElement", + "HTMLAnchorElement", + "HTMLAreaElement", + "HTMLBRElement", + "HTMLButtonElement", + "HTMLCanvasElement", + "HTMLDataElement", + "HTMLDataListElement", + "HTMLDetailsElement", + "HTMLDialogElement", + "HTMLDirectoryElement", + "HTMLFieldSetElement", + "HTMLFontElement", + "HTMLFormElement", + "HTMLHtmlElement", + "HTMLImageElement", + "HTMLInputElement", + "HTMLLabelElement", + "HTMLLegendElement", + "HTMLMapElement", + "HTMLMarqueeElement", + "HTMLMediaElement", + "HTMLMeterElement", + "HTMLModElement", + "HTMLOptGroupElement", + "HTMLOptionElement", + "HTMLOutputElement", + "HTMLPictureElement", + "HTMLProgressElement", + "HTMLQuoteElement", + "HTMLScriptElement", + "HTMLSelectElement", + "HTMLSlotElement", + "HTMLSourceElement", + "HTMLSpanElement", + "HTMLTableCaptionElement", + "HTMLTableCellElement", + "HTMLTableColElement", + "HTMLTableElement", + "HTMLTimeElement", + "HTMLTableRowElement", + "HTMLTableSectionElement", + "HTMLTemplateElement", + "HTMLTextAreaElement", + "HTMLUnknownElement", + "HTMLFrameElement", + "HTMLFrameSetElement", + "HTMLIFrameElement", + "HTMLEmbedElement", + "HTMLObjectElement", + "HTMLParamElement", + "HTMLVideoElement", + "HTMLAudioElement", + "HTMLTrackElement", + "HTMLFormControlsCollection", + "SVGElement", + "SVGGraphicsElement", + "SVGSVGElement", + "SVGTitleElement", + "SVGAnimatedString", + "SVGNumber", + "SVGStringList", + "Event", + "CloseEvent", + "CustomEvent", + "MessageEvent", + "ErrorEvent", + "HashChangeEvent", + "PopStateEvent", + "StorageEvent", + "ProgressEvent", + "PageTransitionEvent", + "UIEvent", + "FocusEvent", + "InputEvent", + "MouseEvent", + "KeyboardEvent", + "TouchEvent", + "CompositionEvent", + "WheelEvent", + "BarProp", + "External", + "Location", + "History", + "Screen", + "Crypto", + "Performance", + "Navigator", + "PluginArray", + "MimeTypeArray", + "Plugin", + "MimeType", + "FileReader", + "Blob", + "File", + "FileList", + "ValidityState", + "DOMParser", + "XMLSerializer", + "FormData", + "XMLHttpRequestEventTarget", + "XMLHttpRequestUpload", + "XMLHttpRequest", + "WebSocket", + "NodeFilter", + "NodeIterator", + "TreeWalker", + "AbstractRange", + "Range", + "StaticRange", + "Selection", + "Storage", + "CustomElementRegistry", + "ShadowRoot", + "MutationObserver", + "MutationRecord", + "Headers", + "AbortController", + "AbortSignal", + "ArrayBuffer", + "Image", + "Audio", + "Option" +]; +const OTHER_KEYS = [ + "addEventListener", + "alert", + "atob", + "blur", + "btoa", + "cancelAnimationFrame", + "close", + "confirm", + "createPopup", + "dispatchEvent", + "document", + "focus", + "frames", + "getComputedStyle", + "history", + "innerHeight", + "innerWidth", + "length", + "location", + "matchMedia", + "moveBy", + "moveTo", + "name", + "navigator", + "open", + "outerHeight", + "outerWidth", + "pageXOffset", + "pageYOffset", + "parent", + "postMessage", + "print", + "prompt", + "removeEventListener", + "requestAnimationFrame", + "resizeBy", + "resizeTo", + "screen", + "screenLeft", + "screenTop", + "screenX", + "screenY", + "scroll", + "scrollBy", + "scrollLeft", + "scrollTo", + "scrollTop", + "scrollX", + "scrollY", + "self", + "stop", + "top", + "Window", + "window" +]; +const KEYS = LIVING_KEYS.concat(OTHER_KEYS); + +const skipKeys = [ + "window", + "self", + "top", + "parent" +]; +function getWindowKeys(global, win) { + const keys = new Set(KEYS.concat(Object.getOwnPropertyNames(win)).filter((k) => { + if (skipKeys.includes(k)) + return false; + if (k in global) + return KEYS.includes(k); + return true; + })); + return keys; +} +function isClassLikeName(name) { + return name[0] === name[0].toUpperCase(); +} +function populateGlobal(global, win, options = {}) { + const { bindFunctions = false } = options; + const keys = getWindowKeys(global, win); + const originals = /* @__PURE__ */ new Map(); + const overrideObject = /* @__PURE__ */ new Map(); + for (const key of keys) { + const boundFunction = bindFunctions && typeof win[key] === "function" && !isClassLikeName(key) && win[key].bind(win); + if (KEYS.includes(key) && key in global) + originals.set(key, global[key]); + Object.defineProperty(global, key, { + get() { + if (overrideObject.has(key)) + return overrideObject.get(key); + if (boundFunction) + return boundFunction; + return win[key]; + }, + set(v) { + overrideObject.set(key, v); + }, + configurable: true + }); + } + global.window = global; + global.self = global; + global.top = global; + global.parent = global; + if (global.global) + global.global = global; + skipKeys.forEach((k) => keys.add(k)); + return { + keys, + skipKeys, + originals + }; +} + +var jsdom = { + name: "jsdom", + async setup(global, { jsdom = {} }) { + const { + CookieJar, + JSDOM, + ResourceLoader, + VirtualConsole + } = await importModule("jsdom"); + const { + html = "", + userAgent, + url = "http://localhost:3000", + contentType = "text/html", + pretendToBeVisual = true, + includeNodeLocations = false, + runScripts = "dangerously", + resources, + console = false, + cookieJar = false, + ...restOptions + } = jsdom; + const dom = new JSDOM( + html, + { + pretendToBeVisual, + resources: resources ?? (userAgent ? new ResourceLoader({ userAgent }) : void 0), + runScripts, + url, + virtualConsole: console && global.console ? new VirtualConsole().sendTo(global.console) : void 0, + cookieJar: cookieJar ? new CookieJar() : void 0, + includeNodeLocations, + contentType, + userAgent, + ...restOptions + } + ); + const { keys, originals } = populateGlobal(global, dom.window, { bindFunctions: true }); + return { + teardown(global2) { + keys.forEach((key) => delete global2[key]); + originals.forEach((v, k) => global2[k] = v); + } + }; + } +}; + +var happy = { + name: "happy-dom", + async setup(global) { + const { Window, GlobalWindow } = await importModule("happy-dom"); + const win = new (GlobalWindow || Window)(); + const { keys, originals } = populateGlobal(global, win, { bindFunctions: true }); + return { + teardown(global2) { + win.happyDOM.cancelAsync(); + keys.forEach((key) => delete global2[key]); + originals.forEach((v, k) => global2[k] = v); + } + }; + } +}; + +var edge = { + name: "edge-runtime", + async setup(global) { + const { EdgeVM } = await importModule("@edge-runtime/vm"); + const vm = new EdgeVM({ + extend: (context) => { + context.global = context; + context.Buffer = Buffer; + return context; + } + }); + const { keys, originals } = populateGlobal(global, vm.context, { bindFunctions: true }); + return { + teardown(global2) { + keys.forEach((key) => delete global2[key]); + originals.forEach((v, k) => global2[k] = v); + } + }; + } +}; + +const environments = { + node, + jsdom, + "happy-dom": happy, + "edge-runtime": edge +}; +const envs = Object.keys(environments); +const envPackageNames = { + "jsdom": "jsdom", + "happy-dom": "happy-dom", + "edge-runtime": "@edge-runtime/vm" +}; +const getEnvPackageName = (env) => { + if (env === "node") + return null; + if (env in envPackageNames) + return envPackageNames[env]; + return `vitest-environment-${env}`; +}; + +export { envs as a, environments as e, getEnvPackageName as g, populateGlobal as p }; diff --git a/node_modules/vitest/dist/chunk-install-pkg.6dd2bae6.js b/node_modules/vitest/dist/chunk-install-pkg.6dd2bae6.js new file mode 100644 index 0000000..5b36380 --- /dev/null +++ b/node_modules/vitest/dist/chunk-install-pkg.6dd2bae6.js @@ -0,0 +1,1677 @@ +import require$$0 from 'fs'; +import g from 'path'; +import util from 'util'; +import require$$0$2 from 'child_process'; +import { p as pathKey, s as signalExit, m as mergeStream$1, g as getStream$1, c as crossSpawn$1 } from './vendor-index.7a2cebfe.js'; +import { o as onetime$1 } from './vendor-index.9c919048.js'; +import require$$0$1 from 'os'; +import './vendor-_commonjsHelpers.addc3445.js'; +import 'assert'; +import 'events'; +import 'buffer'; +import 'stream'; + +var findUp$1 = {exports: {}}; + +var locatePath = {exports: {}}; + +class Node { + /// value; + /// next; + + constructor(value) { + this.value = value; + + // TODO: Remove this when targeting Node.js 12. + this.next = undefined; + } +} + +class Queue$1 { + // TODO: Use private class fields when targeting Node.js 12. + // #_head; + // #_tail; + // #_size; + + constructor() { + this.clear(); + } + + enqueue(value) { + const node = new Node(value); + + if (this._head) { + this._tail.next = node; + this._tail = node; + } else { + this._head = node; + this._tail = node; + } + + this._size++; + } + + dequeue() { + const current = this._head; + if (!current) { + return; + } + + this._head = this._head.next; + this._size--; + return current.value; + } + + clear() { + this._head = undefined; + this._tail = undefined; + this._size = 0; + } + + get size() { + return this._size; + } + + * [Symbol.iterator]() { + let current = this._head; + + while (current) { + yield current.value; + current = current.next; + } + } +} + +var yoctoQueue = Queue$1; + +const Queue = yoctoQueue; + +const pLimit$1 = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, ...args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, ...args) => { + queue.enqueue(run.bind(null, fn, resolve, ...args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, ...args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.size + }, + clearQueue: { + value: () => { + queue.clear(); + } + } + }); + + return generator; +}; + +var pLimit_1 = pLimit$1; + +const pLimit = pLimit_1; + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +const pLocate$1 = async (iterable, tester, options) => { + options = { + concurrency: Infinity, + preserveOrder: true, + ...options + }; + + const limit = pLimit(options.concurrency); + + // Start all the promises concurrently with optional limit + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently + const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +}; + +var pLocate_1 = pLocate$1; + +const path$1 = g; +const fs$1 = require$$0; +const {promisify: promisify$1} = util; +const pLocate = pLocate_1; + +const fsStat = promisify$1(fs$1.stat); +const fsLStat = promisify$1(fs$1.lstat); + +const typeMappings = { + directory: 'isDirectory', + file: 'isFile' +}; + +function checkType({type}) { + if (type in typeMappings) { + return; + } + + throw new Error(`Invalid type specified: ${type}`); +} + +const matchType = (type, stat) => type === undefined || stat[typeMappings[type]](); + +locatePath.exports = async (paths, options) => { + options = { + cwd: process.cwd(), + type: 'file', + allowSymlinks: true, + ...options + }; + + checkType(options); + + const statFn = options.allowSymlinks ? fsStat : fsLStat; + + return pLocate(paths, async path_ => { + try { + const stat = await statFn(path$1.resolve(options.cwd, path_)); + return matchType(options.type, stat); + } catch { + return false; + } + }, options); +}; + +locatePath.exports.sync = (paths, options) => { + options = { + cwd: process.cwd(), + allowSymlinks: true, + type: 'file', + ...options + }; + + checkType(options); + + const statFn = options.allowSymlinks ? fs$1.statSync : fs$1.lstatSync; + + for (const path_ of paths) { + try { + const stat = statFn(path$1.resolve(options.cwd, path_)); + + if (matchType(options.type, stat)) { + return path_; + } + } catch {} + } +}; + +var pathExists = {exports: {}}; + +const fs = require$$0; +const {promisify} = util; + +const pAccess = promisify(fs.access); + +pathExists.exports = async path => { + try { + await pAccess(path); + return true; + } catch (_) { + return false; + } +}; + +pathExists.exports.sync = path => { + try { + fs.accessSync(path); + return true; + } catch (_) { + return false; + } +}; + +(function (module) { + const path = g; + const locatePath$1 = locatePath.exports; + const pathExists$1 = pathExists.exports; + + const stop = Symbol('findUp.stop'); + + module.exports = async (name, options = {}) => { + let directory = path.resolve(options.cwd || ''); + const {root} = path.parse(directory); + const paths = [].concat(name); + + const runMatcher = async locateOptions => { + if (typeof name !== 'function') { + return locatePath$1(paths, locateOptions); + } + + const foundPath = await name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath$1([foundPath], locateOptions); + } + + return foundPath; + }; + + // eslint-disable-next-line no-constant-condition + while (true) { + // eslint-disable-next-line no-await-in-loop + const foundPath = await runMatcher({...options, cwd: directory}); + + if (foundPath === stop) { + return; + } + + if (foundPath) { + return path.resolve(directory, foundPath); + } + + if (directory === root) { + return; + } + + directory = path.dirname(directory); + } + }; + + module.exports.sync = (name, options = {}) => { + let directory = path.resolve(options.cwd || ''); + const {root} = path.parse(directory); + const paths = [].concat(name); + + const runMatcher = locateOptions => { + if (typeof name !== 'function') { + return locatePath$1.sync(paths, locateOptions); + } + + const foundPath = name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath$1.sync([foundPath], locateOptions); + } + + return foundPath; + }; + + // eslint-disable-next-line no-constant-condition + while (true) { + const foundPath = runMatcher({...options, cwd: directory}); + + if (foundPath === stop) { + return; + } + + if (foundPath) { + return path.resolve(directory, foundPath); + } + + if (directory === root) { + return; + } + + directory = path.dirname(directory); + } + }; + + module.exports.exists = pathExists$1; + + module.exports.sync.exists = pathExists$1.sync; + + module.exports.stop = stop; +} (findUp$1)); + +var findUp = findUp$1.exports; + +var execa$1 = {exports: {}}; + +var stripFinalNewline$1 = input => { + const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); + const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); + + if (input[input.length - 1] === LF) { + input = input.slice(0, input.length - 1); + } + + if (input[input.length - 1] === CR) { + input = input.slice(0, input.length - 1); + } + + return input; +}; + +var npmRunPath$1 = {exports: {}}; + +(function (module) { + const path = g; + const pathKey$1 = pathKey.exports; + + const npmRunPath = options => { + options = { + cwd: process.cwd(), + path: process.env[pathKey$1()], + execPath: process.execPath, + ...options + }; + + let previous; + let cwdPath = path.resolve(options.cwd); + const result = []; + + while (previous !== cwdPath) { + result.push(path.join(cwdPath, 'node_modules/.bin')); + previous = cwdPath; + cwdPath = path.resolve(cwdPath, '..'); + } + + // Ensure the running `node` binary is used + const execPathDir = path.resolve(options.cwd, options.execPath, '..'); + result.push(execPathDir); + + return result.concat(options.path).join(path.delimiter); + }; + + module.exports = npmRunPath; + // TODO: Remove this for the next major release + module.exports.default = npmRunPath; + + module.exports.env = options => { + options = { + env: process.env, + ...options + }; + + const env = {...options.env}; + const path = pathKey$1({env}); + + options.path = env[path]; + env[path] = module.exports(options); + + return env; + }; +} (npmRunPath$1)); + +var main = {}; + +var signals = {}; + +var core = {}; + +Object.defineProperty(core,"__esModule",{value:true});core.SIGNALS=void 0; + +const SIGNALS=[ +{ +name:"SIGHUP", +number:1, +action:"terminate", +description:"Terminal closed", +standard:"posix"}, + +{ +name:"SIGINT", +number:2, +action:"terminate", +description:"User interruption with CTRL-C", +standard:"ansi"}, + +{ +name:"SIGQUIT", +number:3, +action:"core", +description:"User interruption with CTRL-\\", +standard:"posix"}, + +{ +name:"SIGILL", +number:4, +action:"core", +description:"Invalid machine instruction", +standard:"ansi"}, + +{ +name:"SIGTRAP", +number:5, +action:"core", +description:"Debugger breakpoint", +standard:"posix"}, + +{ +name:"SIGABRT", +number:6, +action:"core", +description:"Aborted", +standard:"ansi"}, + +{ +name:"SIGIOT", +number:6, +action:"core", +description:"Aborted", +standard:"bsd"}, + +{ +name:"SIGBUS", +number:7, +action:"core", +description: +"Bus error due to misaligned, non-existing address or paging error", +standard:"bsd"}, + +{ +name:"SIGEMT", +number:7, +action:"terminate", +description:"Command should be emulated but is not implemented", +standard:"other"}, + +{ +name:"SIGFPE", +number:8, +action:"core", +description:"Floating point arithmetic error", +standard:"ansi"}, + +{ +name:"SIGKILL", +number:9, +action:"terminate", +description:"Forced termination", +standard:"posix", +forced:true}, + +{ +name:"SIGUSR1", +number:10, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, + +{ +name:"SIGSEGV", +number:11, +action:"core", +description:"Segmentation fault", +standard:"ansi"}, + +{ +name:"SIGUSR2", +number:12, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, + +{ +name:"SIGPIPE", +number:13, +action:"terminate", +description:"Broken pipe or socket", +standard:"posix"}, + +{ +name:"SIGALRM", +number:14, +action:"terminate", +description:"Timeout or timer", +standard:"posix"}, + +{ +name:"SIGTERM", +number:15, +action:"terminate", +description:"Termination", +standard:"ansi"}, + +{ +name:"SIGSTKFLT", +number:16, +action:"terminate", +description:"Stack is empty or overflowed", +standard:"other"}, + +{ +name:"SIGCHLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"posix"}, + +{ +name:"SIGCLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"other"}, + +{ +name:"SIGCONT", +number:18, +action:"unpause", +description:"Unpaused", +standard:"posix", +forced:true}, + +{ +name:"SIGSTOP", +number:19, +action:"pause", +description:"Paused", +standard:"posix", +forced:true}, + +{ +name:"SIGTSTP", +number:20, +action:"pause", +description:"Paused using CTRL-Z or \"suspend\"", +standard:"posix"}, + +{ +name:"SIGTTIN", +number:21, +action:"pause", +description:"Background process cannot read terminal input", +standard:"posix"}, + +{ +name:"SIGBREAK", +number:21, +action:"terminate", +description:"User interruption with CTRL-BREAK", +standard:"other"}, + +{ +name:"SIGTTOU", +number:22, +action:"pause", +description:"Background process cannot write to terminal output", +standard:"posix"}, + +{ +name:"SIGURG", +number:23, +action:"ignore", +description:"Socket received out-of-band data", +standard:"bsd"}, + +{ +name:"SIGXCPU", +number:24, +action:"core", +description:"Process timed out", +standard:"bsd"}, + +{ +name:"SIGXFSZ", +number:25, +action:"core", +description:"File too big", +standard:"bsd"}, + +{ +name:"SIGVTALRM", +number:26, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, + +{ +name:"SIGPROF", +number:27, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, + +{ +name:"SIGWINCH", +number:28, +action:"ignore", +description:"Terminal window size changed", +standard:"bsd"}, + +{ +name:"SIGIO", +number:29, +action:"terminate", +description:"I/O is available", +standard:"other"}, + +{ +name:"SIGPOLL", +number:29, +action:"terminate", +description:"Watched event", +standard:"other"}, + +{ +name:"SIGINFO", +number:29, +action:"ignore", +description:"Request for process information", +standard:"other"}, + +{ +name:"SIGPWR", +number:30, +action:"terminate", +description:"Device running out of power", +standard:"systemv"}, + +{ +name:"SIGSYS", +number:31, +action:"core", +description:"Invalid system call", +standard:"other"}, + +{ +name:"SIGUNUSED", +number:31, +action:"terminate", +description:"Invalid system call", +standard:"other"}];core.SIGNALS=SIGNALS; + +var realtime = {}; + +Object.defineProperty(realtime,"__esModule",{value:true});realtime.SIGRTMAX=realtime.getRealtimeSignals=void 0; +const getRealtimeSignals=function(){ +const length=SIGRTMAX-SIGRTMIN+1; +return Array.from({length},getRealtimeSignal); +};realtime.getRealtimeSignals=getRealtimeSignals; + +const getRealtimeSignal=function(value,index){ +return { +name:`SIGRT${index+1}`, +number:SIGRTMIN+index, +action:"terminate", +description:"Application-specific signal (realtime)", +standard:"posix"}; + +}; + +const SIGRTMIN=34; +const SIGRTMAX=64;realtime.SIGRTMAX=SIGRTMAX; + +Object.defineProperty(signals,"__esModule",{value:true});signals.getSignals=void 0;var _os$1=require$$0$1; + +var _core=core; +var _realtime$1=realtime; + + + +const getSignals=function(){ +const realtimeSignals=(0, _realtime$1.getRealtimeSignals)(); +const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); +return signals; +};signals.getSignals=getSignals; + + + + + + + +const normalizeSignal=function({ +name, +number:defaultNumber, +description, +action, +forced=false, +standard}) +{ +const{ +signals:{[name]:constantSignal}}= +_os$1.constants; +const supported=constantSignal!==undefined; +const number=supported?constantSignal:defaultNumber; +return {name,number,description,supported,action,forced,standard}; +}; + +Object.defineProperty(main,"__esModule",{value:true});main.signalsByNumber=main.signalsByName=void 0;var _os=require$$0$1; + +var _signals=signals; +var _realtime=realtime; + + + +const getSignalsByName=function(){ +const signals=(0, _signals.getSignals)(); +return signals.reduce(getSignalByName,{}); +}; + +const getSignalByName=function( +signalByNameMemo, +{name,number,description,supported,action,forced,standard}) +{ +return { +...signalByNameMemo, +[name]:{name,number,description,supported,action,forced,standard}}; + +}; + +const signalsByName$1=getSignalsByName();main.signalsByName=signalsByName$1; + + + + +const getSignalsByNumber=function(){ +const signals=(0, _signals.getSignals)(); +const length=_realtime.SIGRTMAX+1; +const signalsA=Array.from({length},(value,number)=> +getSignalByNumber(number,signals)); + +return Object.assign({},...signalsA); +}; + +const getSignalByNumber=function(number,signals){ +const signal=findSignalByNumber(number,signals); + +if(signal===undefined){ +return {}; +} + +const{name,description,supported,action,forced,standard}=signal; +return { +[number]:{ +name, +number, +description, +supported, +action, +forced, +standard}}; + + +}; + + + +const findSignalByNumber=function(number,signals){ +const signal=signals.find(({name})=>_os.constants.signals[name]===number); + +if(signal!==undefined){ +return signal; +} + +return signals.find(signalA=>signalA.number===number); +}; + +const signalsByNumber=getSignalsByNumber();main.signalsByNumber=signalsByNumber; + +const {signalsByName} = main; + +const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { + if (timedOut) { + return `timed out after ${timeout} milliseconds`; + } + + if (isCanceled) { + return 'was canceled'; + } + + if (errorCode !== undefined) { + return `failed with ${errorCode}`; + } + + if (signal !== undefined) { + return `was killed with ${signal} (${signalDescription})`; + } + + if (exitCode !== undefined) { + return `failed with exit code ${exitCode}`; + } + + return 'failed'; +}; + +const makeError$1 = ({ + stdout, + stderr, + all, + error, + signal, + exitCode, + command, + escapedCommand, + timedOut, + isCanceled, + killed, + parsed: {options: {timeout}} +}) => { + // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. + // We normalize them to `undefined` + exitCode = exitCode === null ? undefined : exitCode; + signal = signal === null ? undefined : signal; + const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; + + const errorCode = error && error.code; + + const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); + const execaMessage = `Command ${prefix}: ${command}`; + const isError = Object.prototype.toString.call(error) === '[object Error]'; + const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; + const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); + + if (isError) { + error.originalMessage = error.message; + error.message = message; + } else { + error = new Error(message); + } + + error.shortMessage = shortMessage; + error.command = command; + error.escapedCommand = escapedCommand; + error.exitCode = exitCode; + error.signal = signal; + error.signalDescription = signalDescription; + error.stdout = stdout; + error.stderr = stderr; + + if (all !== undefined) { + error.all = all; + } + + if ('bufferedData' in error) { + delete error.bufferedData; + } + + error.failed = true; + error.timedOut = Boolean(timedOut); + error.isCanceled = isCanceled; + error.killed = killed && !timedOut; + + return error; +}; + +var error = makeError$1; + +var stdio = {exports: {}}; + +const aliases = ['stdin', 'stdout', 'stderr']; + +const hasAlias = options => aliases.some(alias => options[alias] !== undefined); + +const normalizeStdio$1 = options => { + if (!options) { + return; + } + + const {stdio} = options; + + if (stdio === undefined) { + return aliases.map(alias => options[alias]); + } + + if (hasAlias(options)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); + } + + if (typeof stdio === 'string') { + return stdio; + } + + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } + + const length = Math.max(stdio.length, aliases.length); + return Array.from({length}, (value, index) => stdio[index]); +}; + +stdio.exports = normalizeStdio$1; + +// `ipc` is pushed unless it is already present +stdio.exports.node = options => { + const stdio = normalizeStdio$1(options); + + if (stdio === 'ipc') { + return 'ipc'; + } + + if (stdio === undefined || typeof stdio === 'string') { + return [stdio, stdio, stdio, 'ipc']; + } + + if (stdio.includes('ipc')) { + return stdio; + } + + return [...stdio, 'ipc']; +}; + +const os = require$$0$1; +const onExit = signalExit.exports; + +const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; + +// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior +const spawnedKill$1 = (kill, signal = 'SIGTERM', options = {}) => { + const killResult = kill(signal); + setKillTimeout(kill, signal, options, killResult); + return killResult; +}; + +const setKillTimeout = (kill, signal, options, killResult) => { + if (!shouldForceKill(signal, options, killResult)) { + return; + } + + const timeout = getForceKillAfterTimeout(options); + const t = setTimeout(() => { + kill('SIGKILL'); + }, timeout); + + // Guarded because there's no `.unref()` when `execa` is used in the renderer + // process in Electron. This cannot be tested since we don't run tests in + // Electron. + // istanbul ignore else + if (t.unref) { + t.unref(); + } +}; + +const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => { + return isSigterm(signal) && forceKillAfterTimeout !== false && killResult; +}; + +const isSigterm = signal => { + return signal === os.constants.signals.SIGTERM || + (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); +}; + +const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { + if (forceKillAfterTimeout === true) { + return DEFAULT_FORCE_KILL_TIMEOUT; + } + + if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { + throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); + } + + return forceKillAfterTimeout; +}; + +// `childProcess.cancel()` +const spawnedCancel$1 = (spawned, context) => { + const killResult = spawned.kill(); + + if (killResult) { + context.isCanceled = true; + } +}; + +const timeoutKill = (spawned, signal, reject) => { + spawned.kill(signal); + reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); +}; + +// `timeout` option handling +const setupTimeout$1 = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { + if (timeout === 0 || timeout === undefined) { + return spawnedPromise; + } + + let timeoutId; + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + timeoutKill(spawned, killSignal, reject); + }, timeout); + }); + + const safeSpawnedPromise = spawnedPromise.finally(() => { + clearTimeout(timeoutId); + }); + + return Promise.race([timeoutPromise, safeSpawnedPromise]); +}; + +const validateTimeout$1 = ({timeout}) => { + if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { + throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); + } +}; + +// `cleanup` option handling +const setExitHandler$1 = async (spawned, {cleanup, detached}, timedPromise) => { + if (!cleanup || detached) { + return timedPromise; + } + + const removeExitHandler = onExit(() => { + spawned.kill(); + }); + + return timedPromise.finally(() => { + removeExitHandler(); + }); +}; + +var kill = { + spawnedKill: spawnedKill$1, + spawnedCancel: spawnedCancel$1, + setupTimeout: setupTimeout$1, + validateTimeout: validateTimeout$1, + setExitHandler: setExitHandler$1 +}; + +const isStream$1 = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; + +isStream$1.writable = stream => + isStream$1(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; + +isStream$1.readable = stream => + isStream$1(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; + +isStream$1.duplex = stream => + isStream$1.writable(stream) && + isStream$1.readable(stream); + +isStream$1.transform = stream => + isStream$1.duplex(stream) && + typeof stream._transform === 'function'; + +var isStream_1 = isStream$1; + +const isStream = isStream_1; +const getStream = getStream$1.exports; +const mergeStream = mergeStream$1; + +// `input` option +const handleInput$1 = (spawned, input) => { + // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 + // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 + if (input === undefined || spawned.stdin === undefined) { + return; + } + + if (isStream(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } +}; + +// `all` interleaves `stdout` and `stderr` +const makeAllStream$1 = (spawned, {all}) => { + if (!all || (!spawned.stdout && !spawned.stderr)) { + return; + } + + const mixed = mergeStream(); + + if (spawned.stdout) { + mixed.add(spawned.stdout); + } + + if (spawned.stderr) { + mixed.add(spawned.stderr); + } + + return mixed; +}; + +// On failure, `result.stdout|stderr|all` should contain the currently buffered stream +const getBufferedData = async (stream, streamPromise) => { + if (!stream) { + return; + } + + stream.destroy(); + + try { + return await streamPromise; + } catch (error) { + return error.bufferedData; + } +}; + +const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { + if (!stream || !buffer) { + return; + } + + if (encoding) { + return getStream(stream, {encoding, maxBuffer}); + } + + return getStream.buffer(stream, {maxBuffer}); +}; + +// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) +const getSpawnedResult$1 = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { + const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); + const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); + const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); + + try { + return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); + } catch (error) { + return Promise.all([ + {error, signal: error.signal, timedOut: error.timedOut}, + getBufferedData(stdout, stdoutPromise), + getBufferedData(stderr, stderrPromise), + getBufferedData(all, allPromise) + ]); + } +}; + +const validateInputSync$1 = ({input}) => { + if (isStream(input)) { + throw new TypeError('The `input` option cannot be a stream in sync mode'); + } +}; + +var stream = { + handleInput: handleInput$1, + makeAllStream: makeAllStream$1, + getSpawnedResult: getSpawnedResult$1, + validateInputSync: validateInputSync$1 +}; + +const nativePromisePrototype = (async () => {})().constructor.prototype; +const descriptors = ['then', 'catch', 'finally'].map(property => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property) +]); + +// The return value is a mixin of `childProcess` and `Promise` +const mergePromise$1 = (spawned, promise) => { + for (const [property, descriptor] of descriptors) { + // Starting the main `promise` is deferred to avoid consuming streams + const value = typeof promise === 'function' ? + (...args) => Reflect.apply(descriptor.value, promise(), args) : + descriptor.value.bind(promise); + + Reflect.defineProperty(spawned, property, {...descriptor, value}); + } + + return spawned; +}; + +// Use promises instead of `child_process` events +const getSpawnedPromise$1 = spawned => { + return new Promise((resolve, reject) => { + spawned.on('exit', (exitCode, signal) => { + resolve({exitCode, signal}); + }); + + spawned.on('error', error => { + reject(error); + }); + + if (spawned.stdin) { + spawned.stdin.on('error', error => { + reject(error); + }); + } + }); +}; + +var promise = { + mergePromise: mergePromise$1, + getSpawnedPromise: getSpawnedPromise$1 +}; + +const normalizeArgs = (file, args = []) => { + if (!Array.isArray(args)) { + return [file]; + } + + return [file, ...args]; +}; + +const NO_ESCAPE_REGEXP = /^[\w.-]+$/; +const DOUBLE_QUOTES_REGEXP = /"/g; + +const escapeArg = arg => { + if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) { + return arg; + } + + return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`; +}; + +const joinCommand$1 = (file, args) => { + return normalizeArgs(file, args).join(' '); +}; + +const getEscapedCommand$1 = (file, args) => { + return normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' '); +}; + +const SPACES_REGEXP = / +/g; + +// Handle `execa.command()` +const parseCommand$1 = command => { + const tokens = []; + for (const token of command.trim().split(SPACES_REGEXP)) { + // Allow spaces to be escaped by a backslash if not meant as a delimiter + const previousToken = tokens[tokens.length - 1]; + if (previousToken && previousToken.endsWith('\\')) { + // Merge previous token with current one + tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; + } else { + tokens.push(token); + } + } + + return tokens; +}; + +var command = { + joinCommand: joinCommand$1, + getEscapedCommand: getEscapedCommand$1, + parseCommand: parseCommand$1 +}; + +const path = g; +const childProcess = require$$0$2; +const crossSpawn = crossSpawn$1.exports; +const stripFinalNewline = stripFinalNewline$1; +const npmRunPath = npmRunPath$1.exports; +const onetime = onetime$1.exports; +const makeError = error; +const normalizeStdio = stdio.exports; +const {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = kill; +const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = stream; +const {mergePromise, getSpawnedPromise} = promise; +const {joinCommand, parseCommand, getEscapedCommand} = command; + +const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; + +const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { + const env = extendEnv ? {...process.env, ...envOption} : envOption; + + if (preferLocal) { + return npmRunPath.env({env, cwd: localDir, execPath}); + } + + return env; +}; + +const handleArguments = (file, args, options = {}) => { + const parsed = crossSpawn._parse(file, args, options); + file = parsed.command; + args = parsed.args; + options = parsed.options; + + options = { + maxBuffer: DEFAULT_MAX_BUFFER, + buffer: true, + stripFinalNewline: true, + extendEnv: true, + preferLocal: false, + localDir: options.cwd || process.cwd(), + execPath: process.execPath, + encoding: 'utf8', + reject: true, + cleanup: true, + all: false, + windowsHide: true, + ...options + }; + + options.env = getEnv(options); + + options.stdio = normalizeStdio(options); + + if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') { + // #116 + args.unshift('/q'); + } + + return {file, args, options, parsed}; +}; + +const handleOutput = (options, value, error) => { + if (typeof value !== 'string' && !Buffer.isBuffer(value)) { + // When `execa.sync()` errors, we normalize it to '' to mimic `execa()` + return error === undefined ? undefined : ''; + } + + if (options.stripFinalNewline) { + return stripFinalNewline(value); + } + + return value; +}; + +const execa = (file, args, options) => { + const parsed = handleArguments(file, args, options); + const command = joinCommand(file, args); + const escapedCommand = getEscapedCommand(file, args); + + validateTimeout(parsed.options); + + let spawned; + try { + spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options); + } catch (error) { + // Ensure the returned error is always both a promise and a child process + const dummySpawned = new childProcess.ChildProcess(); + const errorPromise = Promise.reject(makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + escapedCommand, + parsed, + timedOut: false, + isCanceled: false, + killed: false + })); + return mergePromise(dummySpawned, errorPromise); + } + + const spawnedPromise = getSpawnedPromise(spawned); + const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); + const processDone = setExitHandler(spawned, parsed.options, timedPromise); + + const context = {isCanceled: false}; + + spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); + spawned.cancel = spawnedCancel.bind(null, spawned, context); + + const handlePromise = async () => { + const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); + const stdout = handleOutput(parsed.options, stdoutResult); + const stderr = handleOutput(parsed.options, stderrResult); + const all = handleOutput(parsed.options, allResult); + + if (error || exitCode !== 0 || signal !== null) { + const returnedError = makeError({ + error, + exitCode, + signal, + stdout, + stderr, + all, + command, + escapedCommand, + parsed, + timedOut, + isCanceled: context.isCanceled, + killed: spawned.killed + }); + + if (!parsed.options.reject) { + return returnedError; + } + + throw returnedError; + } + + return { + command, + escapedCommand, + exitCode: 0, + stdout, + stderr, + all, + failed: false, + timedOut: false, + isCanceled: false, + killed: false + }; + }; + + const handlePromiseOnce = onetime(handlePromise); + + handleInput(spawned, parsed.options.input); + + spawned.all = makeAllStream(spawned, parsed.options); + + return mergePromise(spawned, handlePromiseOnce); +}; + +execa$1.exports = execa; + +execa$1.exports.sync = (file, args, options) => { + const parsed = handleArguments(file, args, options); + const command = joinCommand(file, args); + const escapedCommand = getEscapedCommand(file, args); + + validateInputSync(parsed.options); + + let result; + try { + result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options); + } catch (error) { + throw makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + escapedCommand, + parsed, + timedOut: false, + isCanceled: false, + killed: false + }); + } + + const stdout = handleOutput(parsed.options, result.stdout, result.error); + const stderr = handleOutput(parsed.options, result.stderr, result.error); + + if (result.error || result.status !== 0 || result.signal !== null) { + const error = makeError({ + stdout, + stderr, + error: result.error, + signal: result.signal, + exitCode: result.status, + command, + escapedCommand, + parsed, + timedOut: result.error && result.error.code === 'ETIMEDOUT', + isCanceled: false, + killed: result.signal !== null + }); + + if (!parsed.options.reject) { + return error; + } + + throw error; + } + + return { + command, + escapedCommand, + exitCode: 0, + stdout, + stderr, + failed: false, + timedOut: false, + isCanceled: false, + killed: false + }; +}; + +execa$1.exports.command = (command, options) => { + const [file, ...args] = parseCommand(command); + return execa(file, args, options); +}; + +execa$1.exports.commandSync = (command, options) => { + const [file, ...args] = parseCommand(command); + return execa.sync(file, args, options); +}; + +execa$1.exports.node = (scriptPath, args, options = {}) => { + if (args && !Array.isArray(args) && typeof args === 'object') { + options = args; + args = []; + } + + const stdio = normalizeStdio.node(options); + const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect')); + + const { + nodePath = process.execPath, + nodeOptions = defaultExecArgv + } = options; + + return execa( + nodePath, + [ + ...nodeOptions, + scriptPath, + ...(Array.isArray(args) ? args : []) + ], + { + ...options, + stdin: undefined, + stdout: undefined, + stderr: undefined, + stdio, + shell: false + } + ); +}; + +// src/detect.ts +var AGENTS = ["pnpm", "yarn", "npm", "pnpm@6", "yarn@berry", "bun"]; +var LOCKS = { + "bun.lockb": "bun", + "pnpm-lock.yaml": "pnpm", + "yarn.lock": "yarn", + "package-lock.json": "npm", + "npm-shrinkwrap.json": "npm" +}; +async function detectPackageManager(cwd = process.cwd()) { + let agent = null; + const lockPath = await findUp(Object.keys(LOCKS), { cwd }); + let packageJsonPath; + if (lockPath) + packageJsonPath = g.resolve(lockPath, "../package.json"); + else + packageJsonPath = await findUp("package.json", { cwd }); + if (packageJsonPath && require$$0.existsSync(packageJsonPath)) { + try { + const pkg = JSON.parse(require$$0.readFileSync(packageJsonPath, "utf8")); + if (typeof pkg.packageManager === "string") { + const [name, version] = pkg.packageManager.split("@"); + if (name === "yarn" && parseInt(version) > 1) + agent = "yarn@berry"; + else if (name === "pnpm" && parseInt(version) < 7) + agent = "pnpm@6"; + else if (name in AGENTS) + agent = name; + else + console.warn("[ni] Unknown packageManager:", pkg.packageManager); + } + } catch { + } + } + if (!agent && lockPath) + agent = LOCKS[g.basename(lockPath)]; + return agent; +} +async function installPackage(names, options = {}) { + const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm"; + const [agent] = detectedAgent.split("@"); + if (!Array.isArray(names)) + names = [names]; + const args = options.additionalArgs || []; + if (options.preferOffline) { + if (detectedAgent === "yarn@berry") + args.unshift("--cached"); + else + args.unshift("--prefer-offline"); + } + return execa$1.exports( + agent, + [ + agent === "yarn" ? "add" : "install", + options.dev ? "-D" : "", + ...args, + ...names + ].filter(Boolean), + { + stdio: options.silent ? "ignore" : "inherit", + cwd: options.cwd + } + ); +} + +export { detectPackageManager, installPackage }; diff --git a/node_modules/vitest/dist/chunk-integrations-coverage.44413252.js b/node_modules/vitest/dist/chunk-integrations-coverage.44413252.js new file mode 100644 index 0000000..aa3809e --- /dev/null +++ b/node_modules/vitest/dist/chunk-integrations-coverage.44413252.js @@ -0,0 +1,240 @@ +import { importModule } from 'local-pkg'; + +/* +How it works: +`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value. +*/ + +class Node { + value; + next; + + constructor(value) { + this.value = value; + } +} + +class Queue { + #head; + #tail; + #size; + + constructor() { + this.clear(); + } + + enqueue(value) { + const node = new Node(value); + + if (this.#head) { + this.#tail.next = node; + this.#tail = node; + } else { + this.#head = node; + this.#tail = node; + } + + this.#size++; + } + + dequeue() { + const current = this.#head; + if (!current) { + return; + } + + this.#head = this.#head.next; + this.#size--; + return current.value; + } + + clear() { + this.#head = undefined; + this.#tail = undefined; + this.#size = 0; + } + + get size() { + return this.#size; + } + + * [Symbol.iterator]() { + let current = this.#head; + + while (current) { + yield current.value; + current = current.next; + } + } +} + +function pLimit(concurrency) { + if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, args) => { + queue.enqueue(run.bind(undefined, fn, resolve, args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount, + }, + pendingCount: { + get: () => queue.size, + }, + clearQueue: { + value: () => { + queue.clear(); + }, + }, + }); + + return generator; +} + +const CoverageProviderMap = { + c8: "@vitest/coverage-c8", + istanbul: "@vitest/coverage-istanbul" +}; +async function resolveCoverageProvider(provider) { + if (typeof provider === "string") { + const pkg = CoverageProviderMap[provider]; + if (!pkg) + throw new Error(`Unknown coverage provider: ${provider}`); + return await importModule(pkg); + } else { + return provider; + } +} +async function getCoverageProvider(options) { + if ((options == null ? void 0 : options.enabled) && (options == null ? void 0 : options.provider)) { + const { getProvider } = await resolveCoverageProvider(options.provider); + return await getProvider(); + } + return null; +} +async function takeCoverageInsideWorker(options) { + if (options.enabled && options.provider) { + const { takeCoverage } = await resolveCoverageProvider(options.provider); + return await (takeCoverage == null ? void 0 : takeCoverage()); + } +} + +function interpretTaskModes(suite, namePattern, onlyMode, parentIsOnly, allowOnly) { + const suiteIsOnly = parentIsOnly || suite.mode === "only"; + suite.tasks.forEach((t) => { + const includeTask = suiteIsOnly || t.mode === "only"; + if (onlyMode) { + if (t.type === "suite" && (includeTask || someTasksAreOnly(t))) { + if (t.mode === "only") { + checkAllowOnly(t, allowOnly); + t.mode = "run"; + } + } else if (t.mode === "run" && !includeTask) { + t.mode = "skip"; + } else if (t.mode === "only") { + checkAllowOnly(t, allowOnly); + t.mode = "run"; + } + } + if (t.type === "test") { + if (namePattern && !getTaskFullName(t).match(namePattern)) + t.mode = "skip"; + } else if (t.type === "suite") { + if (t.mode === "skip") + skipAllTasks(t); + else + interpretTaskModes(t, namePattern, onlyMode, includeTask, allowOnly); + } + }); + if (suite.mode === "run") { + if (suite.tasks.length && suite.tasks.every((i) => i.mode !== "run")) + suite.mode = "skip"; + } +} +function getTaskFullName(task) { + return `${task.suite ? `${getTaskFullName(task.suite)} ` : ""}${task.name}`; +} +function someTasksAreOnly(suite) { + return suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t)); +} +function skipAllTasks(suite) { + suite.tasks.forEach((t) => { + if (t.mode === "run") { + t.mode = "skip"; + if (t.type === "suite") + skipAllTasks(t); + } + }); +} +function checkAllowOnly(task, allowOnly) { + if (allowOnly) + return; + task.result = { + state: "fail", + error: new Error("[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error") + }; +} +function generateHash(str) { + let hash = 0; + if (str.length === 0) + return `${hash}`; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash = hash & hash; + } + return `${hash}`; +} +function calculateSuiteHash(parent) { + parent.tasks.forEach((t, idx) => { + t.id = `${parent.id}_${idx}`; + if (t.type === "suite") + calculateSuiteHash(t); + }); +} + +export { CoverageProviderMap as C, getCoverageProvider as a, calculateSuiteHash as c, generateHash as g, interpretTaskModes as i, pLimit as p, someTasksAreOnly as s, takeCoverageInsideWorker as t }; diff --git a/node_modules/vitest/dist/chunk-integrations-globals.3dfaeb99.js b/node_modules/vitest/dist/chunk-integrations-globals.3dfaeb99.js new file mode 100644 index 0000000..8afc232 --- /dev/null +++ b/node_modules/vitest/dist/chunk-integrations-globals.3dfaeb99.js @@ -0,0 +1,27 @@ +import { m as globalApis } from './chunk-utils-env.b861e3a0.js'; +import { i as index } from './chunk-utils-import.2baa69a9.js'; +import 'node:url'; +import 'path'; +import './chunk-runtime-chain.6df5a66b.js'; +import 'util'; +import 'chai'; +import './chunk-mock-date.a1c85759.js'; +import 'node:path'; +import 'picocolors'; +import 'local-pkg'; +import './vendor-_commonjsHelpers.addc3445.js'; +import './chunk-utils-timers.52534f96.js'; +import './vendor-index.723a074f.js'; +import 'tinyspy'; +import './chunk-utils-source-map.60562959.js'; +import './chunk-runtime-rpc.7f83c8a9.js'; +import 'node:fs'; +import 'fs'; + +function registerApiGlobally() { + globalApis.forEach((api) => { + globalThis[api] = index[api]; + }); +} + +export { registerApiGlobally }; diff --git a/node_modules/vitest/dist/chunk-magic-string.3a794426.js b/node_modules/vitest/dist/chunk-magic-string.3a794426.js new file mode 100644 index 0000000..0fac78e --- /dev/null +++ b/node_modules/vitest/dist/chunk-magic-string.3a794426.js @@ -0,0 +1,1510 @@ +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 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; +} + +class BitSet { + constructor(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; + } + + add(n) { + this.bits[n >> 5] |= 1 << (n & 31); + } + + has(n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); + } +} + +class Chunk { + constructor(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + { + this.previous = null; + this.next = null; + } + } + + appendLeft(content) { + this.outro += content; + } + + appendRight(content) { + this.intro = this.intro + content; + } + + clone() { + const chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; + } + + contains(index) { + return this.start < index && index < this.end; + } + + eachNext(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + } + + eachPrevious(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + } + + edit(content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; + } + + prependLeft(content) { + this.outro = content + this.outro; + } + + prependRight(content) { + this.intro = content + this.intro; + } + + split(index) { + const sliceIndex = index - this.start; + + const originalBefore = this.original.slice(0, sliceIndex); + const originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + const newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) newChunk.next.previous = newChunk; + newChunk.previous = this; + this.next = newChunk; + + return newChunk; + } + + toString() { + return this.intro + this.content + this.outro; + } + + trimEnd(rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + } + } + + trimStart(rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.end - trimmed.length); + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + } + } +} + +function getBtoa () { + if (typeof window !== 'undefined' && typeof window.btoa === 'function') { + return (str) => window.btoa(unescape(encodeURIComponent(str))); + } else if (typeof Buffer === 'function') { + return (str) => Buffer.from(str, 'utf-8').toString('base64'); + } else { + return () => { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); + }; + } +} + +const btoa = /*#__PURE__*/ getBtoa(); + +class SourceMap { + constructor(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode(properties.mappings); + } + + toString() { + return JSON.stringify(this); + } + + toUrl() { + return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); + } +} + +function guessIndent(code) { + const lines = code.split('\n'); + + const tabbed = lines.filter((line) => /^\t+/.test(line)); + const spaced = lines.filter((line) => /^ {2,}/.test(line)); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + const min = spaced.reduce((previous, current) => { + const numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + const fromParts = from.split(/[/\\]/); + const toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + let i = fromParts.length; + while (i--) fromParts[i] = '..'; + } + + return fromParts.concat(toParts).join('/'); +} + +const toString = Object.prototype.toString; + +function isObject(thing) { + return toString.call(thing) === '[object Object]'; +} + +function getLocator(source) { + const originalLines = source.split('\n'); + const lineOffsets = []; + + for (let i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + let i = 0; + let j = lineOffsets.length; + while (i < j) { + const m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + const line = i - 1; + const column = index - lineOffsets[line]; + return { line, column }; + }; +} + +class Mappings { + constructor(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + } + + addEdit(sourceIndex, content, loc, nameIndex) { + if (content.length) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + } else if (this.pending) { + this.rawSegments.push(this.pending); + } + + this.advance(content); + this.pending = null; + } + + addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { + let originalCharIndex = chunk.start; + let first = true; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; + } + + advance(str) { + if (!str) return; + + const lines = str.split('\n'); + + if (lines.length > 1) { + for (let i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; + } +} + +const n = '\n'; + +const warned = { + insertLeft: false, + insertRight: false, + storeName: false, +}; + +class MagicString { + constructor(string, options = {}) { + const chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: undefined }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; + } + + addSourcemapLocation(char) { + this.sourcemapLocations.add(char); + } + + append(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.outro += content; + return this; + } + + appendLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + } + + appendRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + } + + clone() { + const cloned = new MagicString(this.original, { filename: this.filename }); + + let originalChunk = this.firstChunk; + let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + const nextOriginalChunk = originalChunk.next; + const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; + } + + generateDecodedMap(options) { + options = options || {}; + + const sourceIndex = 0; + const names = Object.keys(this.storedNames); + const mappings = new Mappings(options.hires); + + const locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1 + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : null, + sources: [options.source ? getRelativePath(options.file || '', options.source) : null], + sourcesContent: options.includeContent ? [this.original] : [null], + names, + mappings: mappings.raw, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + _ensureindentStr() { + if (this.indentStr === undefined) { + this.indentStr = guessIndent(this.original); + } + } + + _getRawIndentString() { + this._ensureindentStr(); + return this.indentStr; + } + + getIndentString() { + this._ensureindentStr(); + return this.indentStr === null ? '\t' : this.indentStr; + } + + indent(indentStr, options) { + const pattern = /^[^\r\n]/gm; + + if (isObject(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + if (indentStr === undefined) { + this._ensureindentStr(); + indentStr = this.indentStr || '\t'; + } + + if (indentStr === '') return this; // noop + + options = options || {}; + + // Process exclusion ranges + const isExcluded = {}; + + if (options.exclude) { + const exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach((exclusion) => { + for (let i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + let shouldIndentNextCharacter = options.indentStart !== false; + const replacer = (match) => { + if (shouldIndentNextCharacter) return `${indentStr}${match}`; + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + let charIndex = 0; + let chunk = this.firstChunk; + + while (chunk) { + const end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + const char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; + } + + insert() { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' + ); + } + + insertLeft(index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); + } + + insertRight(index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); + } + + move(start, end, index) { + if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); + + this._split(start); + this._split(end); + this._split(index); + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + const oldLeft = first.previous; + const oldRight = last.next; + + const newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) return this; + const newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) oldLeft.next = oldRight; + if (oldRight) oldRight.previous = oldLeft; + + if (newLeft) newLeft.next = first; + if (newRight) newRight.previous = last; + + if (!first.previous) this.firstChunk = last.next; + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) this.firstChunk = first; + if (!newRight) this.lastChunk = last; + return this; + } + + overwrite(start, end, content, options) { + options = options || {}; + return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); + } + + update(start, end, content, options) { + if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); + + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (end > this.original.length) throw new Error('end is out of bounds'); + if (start === end) + throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' + ); + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + const storeName = options !== undefined ? options.storeName : false; + const overwrite = options !== undefined ? options.overwrite : false; + + if (storeName) { + const original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { + writable: true, + value: true, + enumerable: true, + }); + } + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + if (first) { + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, !overwrite); + } else { + // must be inserting at the end + const newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; + } + + prepend(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.intro = content + this.intro; + return this; + } + + prependLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + } + + prependRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + } + + remove(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + lastChar() { + if (this.outro.length) return this.outro[this.outro.length - 1]; + let chunk = this.lastChunk; + do { + if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; + if (chunk.content.length) return chunk.content[chunk.content.length - 1]; + if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; + } while ((chunk = chunk.previous)); + if (this.intro.length) return this.intro[this.intro.length - 1]; + return ''; + } + + lastLine() { + let lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); + let lineStr = this.outro; + let chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; + return this.intro + lineStr; + } + + slice(start = 0, end = this.original.length) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + let result = ''; + + // find start chunk + let chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); + + const startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + const containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); + + const sliceStart = startChunk === chunk ? start - chunk.start : 0; + const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; + } + + // TODO deprecate this? not really very useful + snip(start, end) { + const clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; + } + + _split(index) { + if (this.byStart[index] || this.byEnd[index]) return; + + let chunk = this.lastSearchedChunk; + const searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) return this._splitChunk(chunk, index); + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + } + + _splitChunk(chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + const loc = getLocator(this.original)(index); + throw new Error( + `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")` + ); + } + + const newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) this.lastChunk = newChunk; + + this.lastSearchedChunk = chunk; + return true; + } + + toString() { + let str = this.intro; + + let chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; + } + + isEmpty() { + let chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + return false; + } while ((chunk = chunk.next)); + return true; + } + + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimEndAborted(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + let chunk = this.lastChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.previous; + } while (chunk); + + return false; + } + + trimEnd(charType) { + this.trimEndAborted(charType); + return this; + } + trimStartAborted(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + let chunk = this.firstChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) this.lastChunk = chunk.next; + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.next; + } while (chunk); + + return false; + } + + trimStart(charType) { + this.trimStartAborted(charType); + return this; + } + + hasChanged() { + return this.original !== this.toString(); + } + + _replaceRegexp(searchValue, replacement) { + function getReplacement(match, str) { + if (typeof replacement === 'string') { + return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter + if (i === '$') return '$'; + if (i === '&') return match[0]; + const num = +i; + if (num < match.length) return match[+i]; + return `$${i}`; + }); + } else { + return replacement(...match, match.index, str, match.groups); + } + } + function matchAll(re, str) { + let match; + const matches = []; + while ((match = re.exec(str))) { + matches.push(match); + } + return matches; + } + if (searchValue.global) { + const matches = matchAll(searchValue, this.original); + matches.forEach((match) => { + if (match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original) + ); + }); + } else { + const match = this.original.match(searchValue); + if (match && match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original) + ); + } + return this; + } + + _replaceString(string, replacement) { + const { original } = this; + const index = original.indexOf(string); + + if (index !== -1) { + this.overwrite(index, index + string.length, replacement); + } + + return this; + } + + replace(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceString(searchValue, replacement); + } + + return this._replaceRegexp(searchValue, replacement); + } + + _replaceAllString(string, replacement) { + const { original } = this; + const stringLength = string.length; + for ( + let index = original.indexOf(string); + index !== -1; + index = original.indexOf(string, index + stringLength) + ) { + this.overwrite(index, index + stringLength, replacement); + } + + return this; + } + + replaceAll(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceAllString(searchValue, replacement); + } + + if (!searchValue.global) { + throw new TypeError( + 'MagicString.prototype.replaceAll called with a non-global RegExp argument' + ); + } + + return this._replaceRegexp(searchValue, replacement); + } +} + +const hasOwnProp = Object.prototype.hasOwnProperty; + +class Bundle { + constructor(options = {}) { + this.intro = options.intro || ''; + this.separator = options.separator !== undefined ? options.separator : '\n'; + this.sources = []; + this.uniqueSources = []; + this.uniqueSourceIndexByFilename = {}; + } + + addSource(source) { + if (source instanceof MagicString) { + return this.addSource({ + content: source, + filename: source.filename, + separator: this.separator, + }); + } + + if (!isObject(source) || !source.content) { + throw new Error( + 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`' + ); + } + + ['filename', 'indentExclusionRanges', 'separator'].forEach((option) => { + if (!hasOwnProp.call(source, option)) source[option] = source.content[option]; + }); + + if (source.separator === undefined) { + // TODO there's a bunch of this sort of thing, needs cleaning up + source.separator = this.separator; + } + + if (source.filename) { + if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) { + this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length; + this.uniqueSources.push({ filename: source.filename, content: source.content.original }); + } else { + const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]]; + if (source.content.original !== uniqueSource.content) { + throw new Error(`Illegal source: same filename (${source.filename}), different contents`); + } + } + } + + this.sources.push(source); + return this; + } + + append(str, options) { + this.addSource({ + content: new MagicString(str), + separator: (options && options.separator) || '', + }); + + return this; + } + + clone() { + const bundle = new Bundle({ + intro: this.intro, + separator: this.separator, + }); + + this.sources.forEach((source) => { + bundle.addSource({ + filename: source.filename, + content: source.content.clone(), + separator: source.separator, + }); + }); + + return bundle; + } + + generateDecodedMap(options = {}) { + const names = []; + this.sources.forEach((source) => { + Object.keys(source.content.storedNames).forEach((name) => { + if (!~names.indexOf(name)) names.push(name); + }); + }); + + const mappings = new Mappings(options.hires); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.sources.forEach((source, i) => { + if (i > 0) { + mappings.advance(this.separator); + } + + const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1; + const magicString = source.content; + const locate = getLocator(magicString.original); + + if (magicString.intro) { + mappings.advance(magicString.intro); + } + + magicString.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (source.filename) { + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1 + ); + } else { + mappings.addUneditedChunk( + sourceIndex, + chunk, + magicString.original, + loc, + magicString.sourcemapLocations + ); + } + } else { + mappings.advance(chunk.content); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + if (magicString.outro) { + mappings.advance(magicString.outro); + } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : null, + sources: this.uniqueSources.map((source) => { + return options.file ? getRelativePath(options.file, source.filename) : source.filename; + }), + sourcesContent: this.uniqueSources.map((source) => { + return options.includeContent ? source.content : null; + }), + names, + mappings: mappings.raw, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + getIndentString() { + const indentStringCounts = {}; + + this.sources.forEach((source) => { + const indentStr = source.content._getRawIndentString(); + + if (indentStr === null) return; + + if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0; + indentStringCounts[indentStr] += 1; + }); + + return ( + Object.keys(indentStringCounts).sort((a, b) => { + return indentStringCounts[a] - indentStringCounts[b]; + })[0] || '\t' + ); + } + + indent(indentStr) { + if (!arguments.length) { + indentStr = this.getIndentString(); + } + + if (indentStr === '') return this; // noop + + let trailingNewline = !this.intro || this.intro.slice(-1) === '\n'; + + this.sources.forEach((source, i) => { + const separator = source.separator !== undefined ? source.separator : this.separator; + const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator)); + + source.content.indent(indentStr, { + exclude: source.indentExclusionRanges, + indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator ) + }); + + trailingNewline = source.content.lastChar() === '\n'; + }); + + if (this.intro) { + this.intro = + indentStr + + this.intro.replace(/^[^\n]/gm, (match, index) => { + return index > 0 ? indentStr + match : match; + }); + } + + return this; + } + + prepend(str) { + this.intro = str + this.intro; + return this; + } + + toString() { + const body = this.sources + .map((source, i) => { + const separator = source.separator !== undefined ? source.separator : this.separator; + const str = (i > 0 ? separator : '') + source.content.toString(); + + return str; + }) + .join(''); + + return this.intro + body; + } + + isEmpty() { + if (this.intro.length && this.intro.trim()) return false; + if (this.sources.some((source) => !source.content.isEmpty())) return false; + return true; + } + + length() { + return this.sources.reduce( + (length, source) => length + source.content.length(), + this.intro.length + ); + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimStart(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + this.intro = this.intro.replace(rx, ''); + + if (!this.intro) { + let source; + let i = 0; + + do { + source = this.sources[i++]; + if (!source) { + break; + } + } while (!source.content.trimStartAborted(charType)); + } + + return this; + } + + trimEnd(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + let source; + let i = this.sources.length - 1; + + do { + source = this.sources[i--]; + if (!source) { + this.intro = this.intro.replace(rx, ''); + break; + } + } while (!source.content.trimEndAborted(charType)); + + return this; + } +} + +export { Bundle, SourceMap, MagicString as default }; diff --git a/node_modules/vitest/dist/chunk-mock-date.a1c85759.js b/node_modules/vitest/dist/chunk-mock-date.a1c85759.js new file mode 100644 index 0000000..d43e62e --- /dev/null +++ b/node_modules/vitest/dist/chunk-mock-date.a1c85759.js @@ -0,0 +1,341 @@ +import { relative } from 'node:path'; +import c from 'picocolors'; +import { isPackageExists } from 'local-pkg'; +import { i as isNode, a as isBrowser, r as relative$1, E as EXIT_CODE_RESTART } from './chunk-utils-env.b861e3a0.js'; + +const RealDate = Date; +let now = null; +class MockDate extends RealDate { + constructor(y, m, d, h, M, s, ms) { + super(); + let date; + switch (arguments.length) { + case 0: + if (now !== null) + date = new RealDate(now.valueOf()); + else + date = new RealDate(); + break; + case 1: + date = new RealDate(y); + break; + default: + d = typeof d === "undefined" ? 1 : d; + h = h || 0; + M = M || 0; + s = s || 0; + ms = ms || 0; + date = new RealDate(y, m, d, h, M, s, ms); + break; + } + return date; + } +} +MockDate.UTC = RealDate.UTC; +MockDate.now = function() { + return new MockDate().valueOf(); +}; +MockDate.parse = function(dateString) { + return RealDate.parse(dateString); +}; +MockDate.toString = function() { + return RealDate.toString(); +}; +function mockDate(date) { + const dateObj = new RealDate(date.valueOf()); + if (isNaN(dateObj.getTime())) + throw new TypeError(`mockdate: The time set is an invalid date: ${date}`); + globalThis.Date = MockDate; + now = dateObj.valueOf(); +} +function resetDate() { + globalThis.Date = RealDate; +} + +function isFinalObj(obj) { + return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype; +} +function collectOwnProperties(obj, collector) { + const collect = typeof collector === "function" ? collector : (key) => collector.add(key); + Object.getOwnPropertyNames(obj).forEach(collect); + Object.getOwnPropertySymbols(obj).forEach(collect); +} +function getAllMockableProperties(obj) { + const allProps = /* @__PURE__ */ new Set(); + let curr = obj; + do { + if (isFinalObj(curr)) + break; + collectOwnProperties(curr, (key) => { + const descriptor = Object.getOwnPropertyDescriptor(curr, key); + if (descriptor) + allProps.add({ key, descriptor }); + }); + } while (curr = Object.getPrototypeOf(curr)); + return Array.from(allProps); +} +function notNullish(v) { + return v != null; +} +function slash(str) { + return str.replace(/\\/g, "/"); +} +const noop = () => { +}; +function getType(value) { + return Object.prototype.toString.apply(value).slice(8, -1); +} +function getOwnProperties(obj) { + const ownProps = /* @__PURE__ */ new Set(); + if (isFinalObj(obj)) + return []; + collectOwnProperties(obj, ownProps); + return Array.from(ownProps); +} +function deepClone(val) { + const seen = /* @__PURE__ */ new WeakMap(); + return clone(val, seen); +} +function clone(val, seen) { + let k, out; + if (seen.has(val)) + return seen.get(val); + if (Array.isArray(val)) { + out = Array(k = val.length); + seen.set(val, out); + while (k--) + out[k] = clone(val[k], seen); + return out; + } + if (Object.prototype.toString.call(val) === "[object Object]") { + out = Object.create(Object.getPrototypeOf(val)); + seen.set(val, out); + const props = getOwnProperties(val); + for (const k2 of props) + out[k2] = clone(val[k2], seen); + return out; + } + return val; +} +function toArray(array) { + if (array === null || array === void 0) + array = []; + if (Array.isArray(array)) + return array; + return [array]; +} +const toString = (v) => Object.prototype.toString.call(v); +const isPlainObject = (val) => toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object"); +function isObject(item) { + return item != null && typeof item === "object" && !Array.isArray(item); +} +function deepMerge(target, ...sources) { + if (!sources.length) + return target; + const source = sources.shift(); + if (source === void 0) + return target; + if (isMergeableObject(target) && isMergeableObject(source)) { + Object.keys(source).forEach((key) => { + if (isMergeableObject(source[key])) { + if (!target[key]) + target[key] = {}; + deepMerge(target[key], source[key]); + } else { + target[key] = source[key]; + } + }); + } + return deepMerge(target, ...sources); +} +function isMergeableObject(item) { + return isPlainObject(item) && !Array.isArray(item); +} +function stdout() { + return console._stdout || process.stdout; +} +function random(seed) { + const x = Math.sin(seed++) * 1e4; + return x - Math.floor(x); +} +function shuffle(array, seed = RealDate.now()) { + let length = array.length; + while (length) { + const index = Math.floor(random(seed) * length--); + const previous = array[length]; + array[length] = array[index]; + array[index] = previous; + ++seed; + } + return array; +} + +function isAtomTest(s) { + return s.type === "test" || s.type === "benchmark"; +} +function getTests(suite) { + return toArray(suite).flatMap((s) => isAtomTest(s) ? [s] : s.tasks.flatMap((c) => isAtomTest(c) ? [c] : getTests(c))); +} +function getSuites(suite) { + return toArray(suite).flatMap((s) => s.type === "suite" ? [s, ...getSuites(s.tasks)] : []); +} +function hasTests(suite) { + return toArray(suite).some((s) => s.tasks.some((c) => isAtomTest(c) || hasTests(c))); +} +function hasFailed(suite) { + return toArray(suite).some((s) => { + var _a; + return ((_a = s.result) == null ? void 0 : _a.state) === "fail" || s.type === "suite" && hasFailed(s.tasks); + }); +} +function hasFailedSnapshot(suite) { + return getTests(suite).some((s) => { + var _a, _b; + return (_b = (_a = s.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.some((e) => e.message.match(/Snapshot .* mismatched/)); + }); +} +function getNames(task) { + const names = [task.name]; + let current = task; + while ((current == null ? void 0 : current.suite) || (current == null ? void 0 : current.file)) { + current = current.suite || current.file; + if (current == null ? void 0 : current.name) + names.unshift(current.name); + } + return names; +} + +function getWorkerState() { + return globalThis.__vitest_worker__; +} +function getCurrentEnvironment() { + return globalThis.__vitest_environment__; +} + +const isWindows = isNode && process.platform === "win32"; +const getRunMode = () => getWorkerState().config.mode; +const isRunningInTest = () => getRunMode() === "test"; +const isRunningInBenchmark = () => getRunMode() === "benchmark"; +const relativePath = isBrowser ? relative : relative$1; +function partitionSuiteChildren(suite) { + let tasksGroup = []; + const tasksGroups = []; + for (const c2 of suite.tasks) { + if (tasksGroup.length === 0 || c2.concurrent === tasksGroup[0].concurrent) { + tasksGroup.push(c2); + } else { + tasksGroups.push(tasksGroup); + tasksGroup = [c2]; + } + } + if (tasksGroup.length > 0) + tasksGroups.push(tasksGroup); + return tasksGroups; +} +function resetModules(modules, resetMocks = false) { + const skipPaths = [ + /\/vitest\/dist\//, + /\/vite-node\/dist\//, + /vitest-virtual-\w+\/dist/, + /@vitest\/dist/, + ...!resetMocks ? [/^mock:/] : [] + ]; + modules.forEach((_, path) => { + if (skipPaths.some((re) => re.test(path))) + return; + modules.delete(path); + }); +} +function getFullName(task) { + return getNames(task).join(c.dim(" > ")); +} +function removeUndefinedValues(obj) { + for (const key in Object.keys(obj)) { + if (obj[key] === void 0) + delete obj[key]; + } + return obj; +} +async function ensurePackageInstalled(dependency, root) { + if (isPackageExists(dependency, { paths: [root] })) + return true; + const promptInstall = !process.env.CI && process.stdout.isTTY; + process.stderr.write(c.red(`${c.inverse(c.red(" MISSING DEP "))} Can not find dependency '${dependency}' + +`)); + if (!promptInstall) + return false; + const prompts = await import('./vendor-index.9f20a9be.js').then(function (n) { return n.i; }); + const { install } = await prompts.prompt({ + type: "confirm", + name: "install", + message: c.reset(`Do you want to install ${c.green(dependency)}?`) + }); + if (install) { + await (await import('./chunk-install-pkg.6dd2bae6.js')).installPackage(dependency, { dev: true }); + process.stderr.write(c.yellow(` +Package ${dependency} installed, re-run the command to start. +`)); + process.exit(EXIT_CODE_RESTART); + return true; + } + return false; +} +function getCallLastIndex(code) { + let charIndex = -1; + let inString = null; + let startedBracers = 0; + let endedBracers = 0; + let beforeChar = null; + while (charIndex <= code.length) { + beforeChar = code[charIndex]; + charIndex++; + const char = code[charIndex]; + const isCharString = char === '"' || char === "'" || char === "`"; + if (isCharString && beforeChar !== "\\") { + if (inString === char) + inString = null; + else if (!inString) + inString = char; + } + if (!inString) { + if (char === "(") + startedBracers++; + if (char === ")") + endedBracers++; + } + if (startedBracers && endedBracers && startedBracers === endedBracers) + return charIndex; + } + return null; +} +isNode ? relative$1 : relative; +class AggregateErrorPonyfill extends Error { + constructor(errors, message = "") { + super(message); + this.errors = [...errors]; + } +} +function createDefer() { + let resolve2 = null; + let reject = null; + const p = new Promise((_resolve, _reject) => { + resolve2 = _resolve; + reject = _reject; + }); + p.resolve = resolve2; + p.reject = reject; + return p; +} +function objectAttr(source, path, defaultValue = void 0) { + const paths = path.replace(/\[(\d+)\]/g, ".$1").split("."); + let result = source; + for (const p of paths) { + result = Object(result)[p]; + if (result === void 0) + return defaultValue; + } + return result; +} + +export { AggregateErrorPonyfill as A, hasFailedSnapshot as B, getSuites as C, deepMerge as D, removeUndefinedValues as E, isWindows as F, stdout as G, getAllMockableProperties as H, RealDate as R, resetModules as a, getCallLastIndex as b, getNames as c, getCurrentEnvironment as d, getFullName as e, isRunningInTest as f, getWorkerState as g, isRunningInBenchmark as h, isObject as i, notNullish as j, relativePath as k, shuffle as l, mockDate as m, noop as n, objectAttr as o, partitionSuiteChildren as p, hasTests as q, resetDate as r, slash as s, toArray as t, hasFailed as u, createDefer as v, deepClone as w, getType as x, ensurePackageInstalled as y, getTests as z }; diff --git a/node_modules/vitest/dist/chunk-node-git.543e964a.js b/node_modules/vitest/dist/chunk-node-git.543e964a.js new file mode 100644 index 0000000..9253c46 --- /dev/null +++ b/node_modules/vitest/dist/chunk-node-git.543e964a.js @@ -0,0 +1,86 @@ +import { b as resolve } from './chunk-utils-env.b861e3a0.js'; +import { e as execa } from './vendor-index.b2fdde54.js'; +import 'node:url'; +import 'path'; +import 'node:buffer'; +import 'node:path'; +import 'node:child_process'; +import 'node:process'; +import './vendor-index.7a2cebfe.js'; +import 'child_process'; +import './vendor-_commonjsHelpers.addc3445.js'; +import 'fs'; +import 'assert'; +import 'events'; +import 'buffer'; +import 'stream'; +import 'util'; +import 'os'; +import 'node:os'; + +class VitestGit { + constructor(cwd) { + this.cwd = cwd; + } + async resolveFilesWithGitCommand(args) { + let result; + try { + result = await execa("git", args, { cwd: this.root }); + } catch (e) { + e.message = e.stderr; + throw e; + } + return result.stdout.split("\n").filter((s) => s !== "").map((changedPath) => resolve(this.root, changedPath)); + } + async findChangedFiles(options) { + const root = await this.getRoot(this.cwd); + if (!root) + return null; + this.root = root; + const changedSince = options.changedSince; + if (typeof changedSince === "string") { + const [committed, staged2, unstaged2] = await Promise.all([ + this.getFilesSince(changedSince), + this.getStagedFiles(), + this.getUnstagedFiles() + ]); + return [...committed, ...staged2, ...unstaged2]; + } + const [staged, unstaged] = await Promise.all([ + this.getStagedFiles(), + this.getUnstagedFiles() + ]); + return [...staged, ...unstaged]; + } + getFilesSince(hash) { + return this.resolveFilesWithGitCommand( + ["diff", "--name-only", `${hash}...HEAD`] + ); + } + getStagedFiles() { + return this.resolveFilesWithGitCommand( + ["diff", "--cached", "--name-only"] + ); + } + getUnstagedFiles() { + return this.resolveFilesWithGitCommand( + [ + "ls-files", + "--other", + "--modified", + "--exclude-standard" + ] + ); + } + async getRoot(cwd) { + const options = ["rev-parse", "--show-cdup"]; + try { + const result = await execa("git", options, { cwd }); + return resolve(cwd, result.stdout); + } catch { + return null; + } + } +} + +export { VitestGit }; diff --git a/node_modules/vitest/dist/chunk-runtime-chain.6df5a66b.js b/node_modules/vitest/dist/chunk-runtime-chain.6df5a66b.js new file mode 100644 index 0000000..aaffef4 --- /dev/null +++ b/node_modules/vitest/dist/chunk-runtime-chain.6df5a66b.js @@ -0,0 +1,2595 @@ +import util$1 from 'util'; +import * as chai$2 from 'chai'; +import { AssertionError, util, expect } from 'chai'; +import { i as isObject$1, b as getCallLastIndex, s as slash, g as getWorkerState, c as getNames, d as getCurrentEnvironment, e as getFullName, o as objectAttr, n as noop, f as isRunningInTest, h as isRunningInBenchmark } from './chunk-mock-date.a1c85759.js'; +import { c as commonjsGlobal } from './vendor-_commonjsHelpers.addc3445.js'; +import c from 'picocolors'; +import { c as createPatch, a as stringify, p as plugins_1, f as format_1, s as safeSetTimeout, b as safeClearTimeout } from './chunk-utils-timers.52534f96.js'; +import { i as isMockFunction } from './vendor-index.723a074f.js'; +import { c as cliTruncate, a as positionToOffset, o as offsetToLineNumber, l as lineSplitRE, b as parseStacktrace } from './chunk-utils-source-map.60562959.js'; +import { r as rpc } from './chunk-runtime-rpc.7f83c8a9.js'; +import fs from 'node:fs'; +import { j as join, d as dirname } from './chunk-utils-env.b861e3a0.js'; +import { promises } from 'fs'; + +function createChainable(keys, fn) { + function create(context) { + const chain2 = function(...args) { + return fn.apply(context, args); + }; + Object.assign(chain2, fn); + chain2.withContext = () => chain2.bind(context); + for (const key of keys) { + Object.defineProperty(chain2, key, { + get() { + return create({ ...context, [key]: true }); + } + }); + } + return chain2; + } + const chain = create({}); + chain.fn = fn; + return chain; +} + +function commonjsRequire(path) { + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); +} + +var chaiSubset = {exports: {}}; + +(function (module, exports) { + (function() { + (function(chaiSubset) { + if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') { + return module.exports = chaiSubset; + } else { + return chai.use(chaiSubset); + } + })(function(chai, utils) { + var Assertion = chai.Assertion; + var assertionPrototype = Assertion.prototype; + + Assertion.addMethod('containSubset', function (expected) { + var actual = utils.flag(this, 'object'); + var showDiff = chai.config.showDiff; + + assertionPrototype.assert.call(this, + compare(expected, actual), + 'expected #{act} to contain subset #{exp}', + 'expected #{act} to not contain subset #{exp}', + expected, + actual, + showDiff + ); + }); + + chai.assert.containSubset = function(val, exp, msg) { + new chai.Assertion(val, msg).to.be.containSubset(exp); + }; + + function compare(expected, actual) { + if (expected === actual) { + return true; + } + if (typeof(actual) !== typeof(expected)) { + return false; + } + if (typeof(expected) !== 'object' || expected === null) { + return expected === actual; + } + if (!!expected && !actual) { + return false; + } + + if (Array.isArray(expected)) { + if (typeof(actual.length) !== 'number') { + return false; + } + var aa = Array.prototype.slice.call(actual); + return expected.every(function (exp) { + return aa.some(function (act) { + return compare(exp, act); + }); + }); + } + + if (expected instanceof Date) { + if (actual instanceof Date) { + return expected.getTime() === actual.getTime(); + } else { + return false; + } + } + + return Object.keys(expected).every(function (key) { + var eo = expected[key]; + var ao = actual[key]; + if (typeof(eo) === 'object' && eo !== null && ao !== null) { + return compare(eo, ao); + } + if (typeof(eo) === 'function') { + return eo(ao); + } + return ao === eo; + }); + } + }); + + }).call(commonjsGlobal); +} (chaiSubset)); + +var Subset = chaiSubset.exports; + +function formatLine(line, outputTruncateLength) { + var _a; + return cliTruncate(line, (outputTruncateLength ?? (((_a = process.stdout) == null ? void 0 : _a.columns) || 80)) - 4); +} +function unifiedDiff(actual, expected, options = {}) { + if (actual === expected) + return ""; + const { outputTruncateLength, outputDiffLines, outputDiffMaxLines, noColor, showLegend = true } = options; + const indent = " "; + const diffLimit = outputDiffLines || 15; + const diffMaxLines = outputDiffMaxLines || 50; + const counts = { + "+": 0, + "-": 0 + }; + let previousState = null; + let previousCount = 0; + const str = (str2) => str2; + const dim = noColor ? str : c.dim; + const green = noColor ? str : c.green; + const red = noColor ? str : c.red; + function preprocess(line) { + if (!line || line.match(/\\ No newline/)) + return; + const char = line[0]; + if ("-+".includes(char)) { + if (previousState !== char) { + previousState = char; + previousCount = 0; + } + previousCount++; + counts[char]++; + if (previousCount === diffLimit) + return dim(`${char} ...`); + else if (previousCount > diffLimit) + return; + } + return line; + } + const msg = createPatch("string", expected, actual); + let lines = msg.split("\n").slice(5).map(preprocess).filter(Boolean); + let moreLines = 0; + const isCompact = counts["+"] === 1 && counts["-"] === 1 && lines.length === 2; + if (lines.length > diffMaxLines) { + const firstDiff = lines.findIndex((line) => line[0] === "-" || line[0] === "+"); + const displayLines = lines.slice(firstDiff - 2, diffMaxLines); + const lastDisplayedIndex = firstDiff - 2 + diffMaxLines; + if (lastDisplayedIndex < lines.length) + moreLines = lines.length - lastDisplayedIndex; + lines = displayLines; + } + let formatted = lines.map((line) => { + line = line.replace(/\\"/g, '"'); + if (line[0] === "-") { + line = formatLine(line.slice(1), outputTruncateLength); + if (isCompact) + return green(line); + return green(`- ${formatLine(line, outputTruncateLength)}`); + } + if (line[0] === "+") { + line = formatLine(line.slice(1), outputTruncateLength); + if (isCompact) + return red(line); + return red(`+ ${formatLine(line, outputTruncateLength)}`); + } + if (line.match(/@@/)) + return "--"; + return ` ${line}`; + }); + if (moreLines) + formatted.push(dim(`... ${moreLines} more lines`)); + if (showLegend) { + if (isCompact) { + formatted = [ + `${green("- Expected")} ${formatted[0]}`, + `${red("+ Received")} ${formatted[1]}` + ]; + } else { + if (formatted[0].includes('"')) + formatted[0] = formatted[0].replace('"', ""); + const last = formatted.length - 1; + if (formatted[last].endsWith('"')) + formatted[last] = formatted[last].slice(0, formatted[last].length - 1); + formatted.unshift( + green(`- Expected - ${counts["-"]}`), + red(`+ Received + ${counts["+"]}`), + "" + ); + } + } + return formatted.map((i) => i ? indent + i : i).join("\n"); +} + +function assertTypes(value, name, types) { + const receivedType = typeof value; + const pass = types.includes(receivedType); + if (!pass) + throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`); +} +function isObject(item) { + return item != null && typeof item === "object" && !Array.isArray(item); +} + +const MATCHERS_OBJECT = Symbol.for("matchers-object"); +const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object"); +const GLOBAL_EXPECT = Symbol.for("expect-global"); +if (!Object.prototype.hasOwnProperty.call(globalThis, MATCHERS_OBJECT)) { + const globalState = /* @__PURE__ */ new WeakMap(); + const matchers = /* @__PURE__ */ Object.create(null); + Object.defineProperty(globalThis, MATCHERS_OBJECT, { + get: () => globalState + }); + Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, { + configurable: true, + get: () => ({ + state: globalState.get(globalThis[GLOBAL_EXPECT]), + matchers + }) + }); +} +const getState = (expect) => globalThis[MATCHERS_OBJECT].get(expect); +const setState = (state, expect) => { + const map = globalThis[MATCHERS_OBJECT]; + const current = map.get(expect) || {}; + Object.assign(current, state); + map.set(expect, current); +}; +const EXPECTED_COLOR = c.green; +const RECEIVED_COLOR = c.red; +const INVERTED_COLOR = c.inverse; +const BOLD_WEIGHT = c.bold; +const DIM_COLOR = c.dim; +function matcherHint(matcherName, received = "received", expected = "expected", options = {}) { + const { + comment = "", + isDirectExpectCall = false, + isNot = false, + promise = "", + secondArgument = "", + expectedColor = EXPECTED_COLOR, + receivedColor = RECEIVED_COLOR, + secondArgumentColor = EXPECTED_COLOR + } = options; + let hint = ""; + let dimString = "expect"; + if (!isDirectExpectCall && received !== "") { + hint += DIM_COLOR(`${dimString}(`) + receivedColor(received); + dimString = ")"; + } + if (promise !== "") { + hint += DIM_COLOR(`${dimString}.`) + promise; + dimString = ""; + } + if (isNot) { + hint += `${DIM_COLOR(`${dimString}.`)}not`; + dimString = ""; + } + if (matcherName.includes(".")) { + dimString += matcherName; + } else { + hint += DIM_COLOR(`${dimString}.`) + matcherName; + dimString = ""; + } + if (expected === "") { + dimString += "()"; + } else { + hint += DIM_COLOR(`${dimString}(`) + expectedColor(expected); + if (secondArgument) + hint += DIM_COLOR(", ") + secondArgumentColor(secondArgument); + dimString = ")"; + } + if (comment !== "") + dimString += ` // ${comment}`; + if (dimString !== "") + hint += DIM_COLOR(dimString); + return hint; +} +const SPACE_SYMBOL = "\xB7"; +const replaceTrailingSpaces = (text) => text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length)); +const printReceived = (object) => RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); +const printExpected = (value) => EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); +function diff(a, b, options) { + return unifiedDiff(stringify(b), stringify(a)); +} +var matcherUtils = /* @__PURE__ */ Object.freeze({ + __proto__: null, + stringify, + EXPECTED_COLOR, + RECEIVED_COLOR, + INVERTED_COLOR, + BOLD_WEIGHT, + DIM_COLOR, + matcherHint, + printReceived, + printExpected, + diff +}); +function equals(a, b, customTesters, strictCheck) { + customTesters = customTesters || []; + return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey); +} +function isAsymmetric(obj) { + return !!obj && typeof obj === "object" && "asymmetricMatch" in obj && isA("Function", obj.asymmetricMatch); +} +function asymmetricMatch(a, b) { + const asymmetricA = isAsymmetric(a); + const asymmetricB = isAsymmetric(b); + if (asymmetricA && asymmetricB) + return void 0; + if (asymmetricA) + return a.asymmetricMatch(b); + if (asymmetricB) + return b.asymmetricMatch(a); +} +function eq(a, b, aStack, bStack, customTesters, hasKey2) { + let result = true; + const asymmetricResult = asymmetricMatch(a, b); + if (asymmetricResult !== void 0) + return asymmetricResult; + for (let i = 0; i < customTesters.length; i++) { + const customTesterResult = customTesters[i](a, b); + if (customTesterResult !== void 0) + return customTesterResult; + } + if (a instanceof Error && b instanceof Error) + return a.message === b.message; + if (Object.is(a, b)) + return true; + if (a === null || b === null) + return a === b; + const className = Object.prototype.toString.call(a); + if (className !== Object.prototype.toString.call(b)) + return false; + switch (className) { + case "[object Boolean]": + case "[object String]": + case "[object Number]": + if (typeof a !== typeof b) { + return false; + } else if (typeof a !== "object" && typeof b !== "object") { + return Object.is(a, b); + } else { + return Object.is(a.valueOf(), b.valueOf()); + } + case "[object Date]": + return isNaN(a) && isNaN(b) || +a === +b; + case "[object RegExp]": + return a.source === b.source && a.flags === b.flags; + } + if (typeof a !== "object" || typeof b !== "object") + return false; + if (isDomNode(a) && isDomNode(b)) + return a.isEqualNode(b); + let length = aStack.length; + while (length--) { + if (aStack[length] === a) + return bStack[length] === b; + else if (bStack[length] === b) + return false; + } + aStack.push(a); + bStack.push(b); + if (className === "[object Array]" && a.length !== b.length) + return false; + const aKeys = keys(a, hasKey2); + let key; + let size = aKeys.length; + if (keys(b, hasKey2).length !== size) + return false; + while (size--) { + key = aKeys[size]; + result = hasKey2(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey2); + if (!result) + return false; + } + aStack.pop(); + bStack.pop(); + return result; +} +function keys(obj, hasKey2) { + const keys2 = []; + for (const key in obj) { + if (hasKey2(obj, key)) + keys2.push(key); + } + return keys2.concat( + Object.getOwnPropertySymbols(obj).filter( + (symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable + ) + ); +} +function hasDefinedKey(obj, key) { + return hasKey(obj, key) && obj[key] !== void 0; +} +function hasKey(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function isA(typeName, value) { + return Object.prototype.toString.apply(value) === `[object ${typeName}]`; +} +function isDomNode(obj) { + return obj !== null && typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string" && typeof obj.isEqualNode === "function"; +} +const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@"; +const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@"; +const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@"; +function isImmutableUnorderedKeyed(maybeKeyed) { + return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL] && !maybeKeyed[IS_ORDERED_SENTINEL]); +} +function isImmutableUnorderedSet(maybeSet) { + return !!(maybeSet && maybeSet[IS_SET_SENTINEL] && !maybeSet[IS_ORDERED_SENTINEL]); +} +const IteratorSymbol = Symbol.iterator; +const hasIterator = (object) => !!(object != null && object[IteratorSymbol]); +const iterableEquality = (a, b, aStack = [], bStack = []) => { + if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b)) + return void 0; + if (a.constructor !== b.constructor) + return false; + let length = aStack.length; + while (length--) { + if (aStack[length] === a) + return bStack[length] === b; + } + aStack.push(a); + bStack.push(b); + const iterableEqualityWithStack = (a2, b2) => iterableEquality(a2, b2, [...aStack], [...bStack]); + if (a.size !== void 0) { + if (a.size !== b.size) { + return false; + } else if (isA("Set", a) || isImmutableUnorderedSet(a)) { + let allFound = true; + for (const aValue of a) { + if (!b.has(aValue)) { + let has = false; + for (const bValue of b) { + const isEqual = equals(aValue, bValue, [iterableEqualityWithStack]); + if (isEqual === true) + has = true; + } + if (has === false) { + allFound = false; + break; + } + } + } + aStack.pop(); + bStack.pop(); + return allFound; + } else if (isA("Map", a) || isImmutableUnorderedKeyed(a)) { + let allFound = true; + for (const aEntry of a) { + if (!b.has(aEntry[0]) || !equals(aEntry[1], b.get(aEntry[0]), [iterableEqualityWithStack])) { + let has = false; + for (const bEntry of b) { + const matchedKey = equals(aEntry[0], bEntry[0], [ + iterableEqualityWithStack + ]); + let matchedValue = false; + if (matchedKey === true) { + matchedValue = equals(aEntry[1], bEntry[1], [ + iterableEqualityWithStack + ]); + } + if (matchedValue === true) + has = true; + } + if (has === false) { + allFound = false; + break; + } + } + } + aStack.pop(); + bStack.pop(); + return allFound; + } + } + const bIterator = b[IteratorSymbol](); + for (const aValue of a) { + const nextB = bIterator.next(); + if (nextB.done || !equals(aValue, nextB.value, [iterableEqualityWithStack])) + return false; + } + if (!bIterator.next().done) + return false; + aStack.pop(); + bStack.pop(); + return true; +}; +const hasPropertyInObject = (object, key) => { + const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype; + if (shouldTerminate) + return false; + return Object.prototype.hasOwnProperty.call(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key); +}; +const isObjectWithKeys = (a) => isObject(a) && !(a instanceof Error) && !Array.isArray(a) && !(a instanceof Date); +const subsetEquality = (object, subset) => { + const subsetEqualityWithContext = (seenReferences = /* @__PURE__ */ new WeakMap()) => (object2, subset2) => { + if (!isObjectWithKeys(subset2)) + return void 0; + return Object.keys(subset2).every((key) => { + if (isObjectWithKeys(subset2[key])) { + if (seenReferences.has(subset2[key])) + return equals(object2[key], subset2[key], [iterableEquality]); + seenReferences.set(subset2[key], true); + } + const result = object2 != null && hasPropertyInObject(object2, key) && equals(object2[key], subset2[key], [ + iterableEquality, + subsetEqualityWithContext(seenReferences) + ]); + seenReferences.delete(subset2[key]); + return result; + }); + }; + return subsetEqualityWithContext()(object, subset); +}; +const typeEquality = (a, b) => { + if (a == null || b == null || a.constructor === b.constructor) + return void 0; + return false; +}; +const arrayBufferEquality = (a, b) => { + if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) + return void 0; + const dataViewA = new DataView(a); + const dataViewB = new DataView(b); + if (dataViewA.byteLength !== dataViewB.byteLength) + return false; + for (let i = 0; i < dataViewA.byteLength; i++) { + if (dataViewA.getUint8(i) !== dataViewB.getUint8(i)) + return false; + } + return true; +}; +const sparseArrayEquality = (a, b) => { + if (!Array.isArray(a) || !Array.isArray(b)) + return void 0; + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + return equals(a, b, [iterableEquality, typeEquality], true) && equals(aKeys, bKeys); +}; +const generateToBeMessage = (deepEqualityName, expected = "#{this}", actual = "#{exp}") => { + const toBeMessage = `expected ${expected} to be ${actual} // Object.is equality`; + if (["toStrictEqual", "toEqual"].includes(deepEqualityName)) + return `${toBeMessage} + +If it should pass with deep equality, replace "toBe" with "${deepEqualityName}" + +Expected: ${expected} +Received: serializes to the same string +`; + return toBeMessage; +}; +class AsymmetricMatcher$1 { + constructor(sample, inverse = false) { + this.sample = sample; + this.inverse = inverse; + this.$$typeof = Symbol.for("jest.asymmetricMatcher"); + } + getMatcherContext(expect) { + return { + ...getState(expect || globalThis[GLOBAL_EXPECT]), + equals, + isNot: this.inverse, + utils: matcherUtils + }; + } +} +class StringContaining extends AsymmetricMatcher$1 { + constructor(sample, inverse = false) { + if (!isA("String", sample)) + throw new Error("Expected is not a string"); + super(sample, inverse); + } + asymmetricMatch(other) { + const result = isA("String", other) && other.includes(this.sample); + return this.inverse ? !result : result; + } + toString() { + return `String${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "string"; + } +} +class Anything extends AsymmetricMatcher$1 { + asymmetricMatch(other) { + return other != null; + } + toString() { + return "Anything"; + } + toAsymmetricMatcher() { + return "Anything"; + } +} +class ObjectContaining extends AsymmetricMatcher$1 { + constructor(sample, inverse = false) { + super(sample, inverse); + } + getPrototype(obj) { + if (Object.getPrototypeOf) + return Object.getPrototypeOf(obj); + if (obj.constructor.prototype === obj) + return null; + return obj.constructor.prototype; + } + hasProperty(obj, property) { + if (!obj) + return false; + if (Object.prototype.hasOwnProperty.call(obj, property)) + return true; + return this.hasProperty(this.getPrototype(obj), property); + } + asymmetricMatch(other) { + if (typeof this.sample !== "object") { + throw new TypeError( + `You must provide an object to ${this.toString()}, not '${typeof this.sample}'.` + ); + } + let result = true; + for (const property in this.sample) { + if (!this.hasProperty(other, property) || !equals(this.sample[property], other[property])) { + result = false; + break; + } + } + return this.inverse ? !result : result; + } + toString() { + return `Object${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "object"; + } +} +class ArrayContaining extends AsymmetricMatcher$1 { + constructor(sample, inverse = false) { + super(sample, inverse); + } + asymmetricMatch(other) { + if (!Array.isArray(this.sample)) { + throw new TypeError( + `You must provide an array to ${this.toString()}, not '${typeof this.sample}'.` + ); + } + const result = this.sample.length === 0 || Array.isArray(other) && this.sample.every( + (item) => other.some((another) => equals(item, another)) + ); + return this.inverse ? !result : result; + } + toString() { + return `Array${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "array"; + } +} +class Any extends AsymmetricMatcher$1 { + constructor(sample) { + if (typeof sample === "undefined") { + throw new TypeError( + "any() expects to be passed a constructor function. Please pass one or use anything() to match any object." + ); + } + super(sample); + } + fnNameFor(func) { + if (func.name) + return func.name; + const functionToString2 = Function.prototype.toString; + const matches = functionToString2.call(func).match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/); + return matches ? matches[1] : ""; + } + asymmetricMatch(other) { + if (this.sample === String) + return typeof other == "string" || other instanceof String; + if (this.sample === Number) + return typeof other == "number" || other instanceof Number; + if (this.sample === Function) + return typeof other == "function" || other instanceof Function; + if (this.sample === Boolean) + return typeof other == "boolean" || other instanceof Boolean; + if (this.sample === BigInt) + return typeof other == "bigint" || other instanceof BigInt; + if (this.sample === Symbol) + return typeof other == "symbol" || other instanceof Symbol; + if (this.sample === Object) + return typeof other == "object"; + return other instanceof this.sample; + } + toString() { + return "Any"; + } + getExpectedType() { + if (this.sample === String) + return "string"; + if (this.sample === Number) + return "number"; + if (this.sample === Function) + return "function"; + if (this.sample === Object) + return "object"; + if (this.sample === Boolean) + return "boolean"; + return this.fnNameFor(this.sample); + } + toAsymmetricMatcher() { + return `Any<${this.fnNameFor(this.sample)}>`; + } +} +class StringMatching extends AsymmetricMatcher$1 { + constructor(sample, inverse = false) { + if (!isA("String", sample) && !isA("RegExp", sample)) + throw new Error("Expected is not a String or a RegExp"); + super(new RegExp(sample), inverse); + } + asymmetricMatch(other) { + const result = isA("String", other) && this.sample.test(other); + return this.inverse ? !result : result; + } + toString() { + return `String${this.inverse ? "Not" : ""}Matching`; + } + getExpectedType() { + return "string"; + } +} +const JestAsymmetricMatchers = (chai, utils) => { + utils.addMethod( + chai.expect, + "anything", + () => new Anything() + ); + utils.addMethod( + chai.expect, + "any", + (expected) => new Any(expected) + ); + utils.addMethod( + chai.expect, + "stringContaining", + (expected) => new StringContaining(expected) + ); + utils.addMethod( + chai.expect, + "objectContaining", + (expected) => new ObjectContaining(expected) + ); + utils.addMethod( + chai.expect, + "arrayContaining", + (expected) => new ArrayContaining(expected) + ); + utils.addMethod( + chai.expect, + "stringMatching", + (expected) => new StringMatching(expected) + ); + chai.expect.not = { + stringContaining: (expected) => new StringContaining(expected, true), + objectContaining: (expected) => new ObjectContaining(expected, true), + arrayContaining: (expected) => new ArrayContaining(expected, true), + stringMatching: (expected) => new StringMatching(expected, true) + }; +}; +const JestChaiExpect = (chai, utils) => { + function def(name, fn) { + const addMethod = (n) => { + utils.addMethod(chai.Assertion.prototype, n, fn); + utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, n, fn); + }; + if (Array.isArray(name)) + name.forEach((n) => addMethod(n)); + else + addMethod(name); + } + ["throw", "throws", "Throw"].forEach((m) => { + utils.overwriteMethod(chai.Assertion.prototype, m, (_super) => { + return function(...args) { + const promise = utils.flag(this, "promise"); + const object = utils.flag(this, "object"); + const isNot = utils.flag(this, "negate"); + if (promise === "rejects") { + utils.flag(this, "object", () => { + throw object; + }); + } else if (promise === "resolves" && typeof object !== "function") { + if (!isNot) { + const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't"; + const error = { + showDiff: false + }; + throw new AssertionError(message, error, utils.flag(this, "ssfi")); + } else { + return; + } + } + _super.apply(this, args); + }; + }); + }); + def("withTest", function(test) { + utils.flag(this, "vitest-test", test); + return this; + }); + def("toEqual", function(expected) { + const actual = utils.flag(this, "object"); + const equal = equals( + actual, + expected, + [iterableEquality] + ); + return this.assert( + equal, + "expected #{this} to deeply equal #{exp}", + "expected #{this} to not deeply equal #{exp}", + expected, + actual + ); + }); + def("toStrictEqual", function(expected) { + const obj = utils.flag(this, "object"); + const equal = equals( + obj, + expected, + [ + iterableEquality, + typeEquality, + sparseArrayEquality, + arrayBufferEquality + ], + true + ); + return this.assert( + equal, + "expected #{this} to strictly equal #{exp}", + "expected #{this} to not strictly equal #{exp}", + expected, + obj + ); + }); + def("toBe", function(expected) { + const actual = this._obj; + const pass = Object.is(actual, expected); + let deepEqualityName = ""; + if (!pass) { + const toStrictEqualPass = equals( + actual, + expected, + [ + iterableEquality, + typeEquality, + sparseArrayEquality, + arrayBufferEquality + ], + true + ); + if (toStrictEqualPass) { + deepEqualityName = "toStrictEqual"; + } else { + const toEqualPass = equals( + actual, + expected, + [iterableEquality] + ); + if (toEqualPass) + deepEqualityName = "toEqual"; + } + } + return this.assert( + pass, + generateToBeMessage(deepEqualityName), + "expected #{this} not to be #{exp} // Object.is equality", + expected, + actual + ); + }); + def("toMatchObject", function(expected) { + const actual = this._obj; + return this.assert( + equals(actual, expected, [iterableEquality, subsetEquality]), + "expected #{this} to match object #{exp}", + "expected #{this} to not match object #{exp}", + expected, + actual + ); + }); + def("toMatch", function(expected) { + if (typeof expected === "string") + return this.include(expected); + else + return this.match(expected); + }); + def("toContain", function(item) { + return this.contain(item); + }); + def("toContainEqual", function(expected) { + const obj = utils.flag(this, "object"); + const index = Array.from(obj).findIndex((item) => { + return equals(item, expected); + }); + this.assert( + index !== -1, + "expected #{this} to deep equally contain #{exp}", + "expected #{this} to not deep equally contain #{exp}", + expected + ); + }); + def("toBeTruthy", function() { + const obj = utils.flag(this, "object"); + this.assert( + Boolean(obj), + "expected #{this} to be truthy", + "expected #{this} to not be truthy", + obj + ); + }); + def("toBeFalsy", function() { + const obj = utils.flag(this, "object"); + this.assert( + !obj, + "expected #{this} to be falsy", + "expected #{this} to not be falsy", + obj + ); + }); + def("toBeGreaterThan", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert( + actual > expected, + `expected ${actual} to be greater than ${expected}`, + `expected ${actual} to be not greater than ${expected}`, + actual, + expected + ); + }); + def("toBeGreaterThanOrEqual", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert( + actual >= expected, + `expected ${actual} to be greater than or equal to ${expected}`, + `expected ${actual} to be not greater than or equal to ${expected}`, + actual, + expected + ); + }); + def("toBeLessThan", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert( + actual < expected, + `expected ${actual} to be less than ${expected}`, + `expected ${actual} to be not less than ${expected}`, + actual, + expected + ); + }); + def("toBeLessThanOrEqual", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert( + actual <= expected, + `expected ${actual} to be less than or equal to ${expected}`, + `expected ${actual} to be not less than or equal to ${expected}`, + actual, + expected + ); + }); + def("toBeNaN", function() { + return this.be.NaN; + }); + def("toBeUndefined", function() { + return this.be.undefined; + }); + def("toBeNull", function() { + return this.be.null; + }); + def("toBeDefined", function() { + const negate = utils.flag(this, "negate"); + utils.flag(this, "negate", false); + if (negate) + return this.be.undefined; + return this.not.be.undefined; + }); + def("toBeTypeOf", function(expected) { + const actual = typeof this._obj; + const equal = expected === actual; + return this.assert( + equal, + "expected #{this} to be type of #{exp}", + "expected #{this} not to be type of #{exp}", + expected, + actual + ); + }); + def("toBeInstanceOf", function(obj) { + return this.instanceOf(obj); + }); + def("toHaveLength", function(length) { + return this.have.length(length); + }); + def("toHaveProperty", function(...args) { + if (Array.isArray(args[0])) + args[0] = args[0].map((key) => key.replace(/([.[\]])/g, "\\$1")).join("."); + const actual = this._obj; + const [propertyName, expected] = args; + const getValue = () => { + const hasOwn = Object.prototype.hasOwnProperty.call(actual, propertyName); + if (hasOwn) + return { value: actual[propertyName], exists: true }; + return utils.getPathInfo(actual, propertyName); + }; + const { value, exists } = getValue(); + const pass = exists && (args.length === 1 || equals(expected, value)); + const valueString = args.length === 1 ? "" : ` with value ${utils.objDisplay(expected)}`; + return this.assert( + pass, + `expected #{this} to have property "${propertyName}"${valueString}`, + `expected #{this} to not have property "${propertyName}"${valueString}`, + actual + ); + }); + def("toBeCloseTo", function(received, precision = 2) { + const expected = this._obj; + let pass = false; + let expectedDiff = 0; + let receivedDiff = 0; + if (received === Infinity && expected === Infinity) { + pass = true; + } else if (received === -Infinity && expected === -Infinity) { + pass = true; + } else { + expectedDiff = 10 ** -precision / 2; + receivedDiff = Math.abs(expected - received); + pass = receivedDiff < expectedDiff; + } + return this.assert( + pass, + `expected #{this} to be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, + `expected #{this} to not be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, + received, + expected + ); + }); + const assertIsMock = (assertion) => { + if (!isMockFunction(assertion._obj)) + throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`); + }; + const getSpy = (assertion) => { + assertIsMock(assertion); + return assertion._obj; + }; + const ordinalOf = (i) => { + const j = i % 10; + const k = i % 100; + if (j === 1 && k !== 11) + return `${i}st`; + if (j === 2 && k !== 12) + return `${i}nd`; + if (j === 3 && k !== 13) + return `${i}rd`; + return `${i}th`; + }; + const formatCalls = (spy, msg, actualCall) => { + msg += c.gray(` + +Received: +${spy.mock.calls.map((callArg, i) => { + let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call: + +`); + if (actualCall) + methodCall += unifiedDiff(stringify(callArg), stringify(actualCall), { showLegend: false }); + else + methodCall += stringify(callArg).split("\n").map((line) => ` ${line}`).join("\n"); + methodCall += "\n"; + return methodCall; + }).join("\n")}`); + msg += c.gray(` + +Number of calls: ${c.bold(spy.mock.calls.length)} +`); + return msg; + }; + const formatReturns = (spy, msg, actualReturn) => { + msg += c.gray(` + +Received: +${spy.mock.results.map((callReturn, i) => { + let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call return: + +`); + if (actualReturn) + methodCall += unifiedDiff(stringify(callReturn.value), stringify(actualReturn), { showLegend: false }); + else + methodCall += stringify(callReturn).split("\n").map((line) => ` ${line}`).join("\n"); + methodCall += "\n"; + return methodCall; + }).join("\n")}`); + msg += c.gray(` + +Number of calls: ${c.bold(spy.mock.calls.length)} +`); + return msg; + }; + def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + return this.assert( + callCount === number, + `expected "${spyName}" to be called #{exp} times`, + `expected "${spyName}" to not be called #{exp} times`, + number, + callCount + ); + }); + def("toHaveBeenCalledOnce", function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + return this.assert( + callCount === 1, + `expected "${spyName}" to be called once`, + `expected "${spyName}" to not be called once`, + 1, + callCount + ); + }); + def(["toHaveBeenCalled", "toBeCalled"], function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const called = spy.mock.calls.length > 0; + const isNot = utils.flag(this, "negate"); + let msg = utils.getMessage( + this, + [ + called, + `expected "${spyName}" to be called at least once`, + `expected "${spyName}" to not be called at all`, + true, + called + ] + ); + if (called && isNot) + msg += formatCalls(spy, msg); + if (called && isNot || !called && !isNot) { + const err = new Error(msg); + err.name = "AssertionError"; + throw err; + } + }); + def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const pass = spy.mock.calls.some((callArg) => equals(callArg, args, [iterableEquality])); + const isNot = utils.flag(this, "negate"); + let msg = utils.getMessage( + this, + [ + pass, + `expected "${spyName}" to be called with arguments: #{exp}`, + `expected "${spyName}" to not be called with arguments: #{exp}`, + args + ] + ); + if (pass && isNot || !pass && !isNot) { + msg += formatCalls(spy, msg, args); + const err = new Error(msg); + err.name = "AssertionError"; + throw err; + } + }); + def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const nthCall = spy.mock.calls[times - 1]; + this.assert( + equals(nthCall, args, [iterableEquality]), + `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}`, + `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`, + args, + nthCall + ); + }); + def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const lastCall = spy.mock.calls[spy.calls.length - 1]; + this.assert( + equals(lastCall, args, [iterableEquality]), + `expected last "${spyName}" call to have been called with #{exp}`, + `expected last "${spyName}" call to not have been called with #{exp}`, + args, + lastCall + ); + }); + def(["toThrow", "toThrowError"], function(expected) { + if (typeof expected === "string" || typeof expected === "undefined" || expected instanceof RegExp) + return this.throws(expected); + const obj = this._obj; + const promise = utils.flag(this, "promise"); + const isNot = utils.flag(this, "negate"); + let thrown = null; + if (promise === "rejects") { + thrown = obj; + } else if (promise === "resolves" && typeof obj !== "function") { + if (!isNot) { + const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't"; + const error = { + showDiff: false + }; + throw new AssertionError(message, error, utils.flag(this, "ssfi")); + } else { + return; + } + } else { + try { + obj(); + } catch (err) { + thrown = err; + } + } + if (typeof expected === "function") { + const name = expected.name || expected.prototype.constructor.name; + return this.assert( + thrown && thrown instanceof expected, + `expected error to be instance of ${name}`, + `expected error not to be instance of ${name}`, + expected, + thrown + ); + } + if (expected instanceof Error) { + return this.assert( + thrown && expected.message === thrown.message, + `expected error to have message: ${expected.message}`, + `expected error not to have message: ${expected.message}`, + expected.message, + thrown && thrown.message + ); + } + if (typeof expected === "object" && "asymmetricMatch" in expected && typeof expected.asymmetricMatch === "function") { + const matcher = expected; + return this.assert( + thrown && matcher.asymmetricMatch(thrown), + "expected error to match asymmetric matcher", + "expected error not to match asymmetric matcher", + matcher.toString(), + thrown + ); + } + throw new Error(`"toThrow" expects string, RegExp, function, Error instance or asymmetric matcher, got "${typeof expected}"`); + }); + def(["toHaveReturned", "toReturn"], function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const calledAndNotThrew = spy.mock.calls.length > 0 && !spy.mock.results.some(({ type }) => type === "throw"); + this.assert( + calledAndNotThrew, + `expected "${spyName}" to be successfully called at least once`, + `expected "${spyName}" to not be successfully called`, + calledAndNotThrew, + !calledAndNotThrew + ); + }); + def(["toHaveReturnedTimes", "toReturnTimes"], function(times) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const successfulReturns = spy.mock.results.reduce((success, { type }) => type === "throw" ? success : ++success, 0); + this.assert( + successfulReturns === times, + `expected "${spyName}" to be successfully called ${times} times`, + `expected "${spyName}" to not be successfully called ${times} times`, + `expected number of returns: ${times}`, + `received number of returns: ${successfulReturns}` + ); + }); + def(["toHaveReturnedWith", "toReturnWith"], function(value) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const pass = spy.mock.results.some(({ type, value: result }) => type === "return" && equals(value, result)); + const isNot = utils.flag(this, "negate"); + let msg = utils.getMessage( + this, + [ + pass, + `expected "${spyName}" to return with: #{exp} at least once`, + `expected "${spyName}" to not return with: #{exp}`, + value + ] + ); + if (pass && isNot || !pass && !isNot) { + msg = formatReturns(spy, msg, value); + const err = new Error(msg); + err.name = "AssertionError"; + throw err; + } + }); + def(["toHaveLastReturnedWith", "lastReturnedWith"], function(value) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const { value: lastResult } = spy.mock.results[spy.returns.length - 1]; + const pass = equals(lastResult, value); + this.assert( + pass, + `expected last "${spyName}" call to return #{exp}`, + `expected last "${spyName}" call to not return #{exp}`, + value, + lastResult + ); + }); + def(["toHaveNthReturnedWith", "nthReturnedWith"], function(nthCall, value) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const isNot = utils.flag(this, "negate"); + const { type: callType, value: callResult } = spy.mock.results[nthCall - 1]; + const ordinalCall = `${ordinalOf(nthCall)} call`; + if (!isNot && callType === "throw") + chai.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`); + const nthCallReturn = equals(callResult, value); + this.assert( + nthCallReturn, + `expected ${ordinalCall} "${spyName}" call to return #{exp}`, + `expected ${ordinalCall} "${spyName}" call to not return #{exp}`, + value, + callResult + ); + }); + def("toSatisfy", function(matcher, message) { + return this.be.satisfy(matcher, message); + }); + utils.addProperty(chai.Assertion.prototype, "resolves", function __VITEST_RESOLVES__() { + utils.flag(this, "promise", "resolves"); + utils.flag(this, "error", new Error("resolves")); + const obj = utils.flag(this, "object"); + if (typeof (obj == null ? void 0 : obj.then) !== "function") + throw new TypeError(`You must provide a Promise to expect() when using .resolves, not '${typeof obj}'.`); + const proxy = new Proxy(this, { + get: (target, key, receiver) => { + const result = Reflect.get(target, key, receiver); + if (typeof result !== "function") + return result instanceof chai.Assertion ? proxy : result; + return async (...args) => { + return obj.then( + (value) => { + utils.flag(this, "object", value); + return result.call(this, ...args); + }, + (err) => { + throw new Error(`promise rejected "${String(err)}" instead of resolving`); + } + ); + }; + } + }); + return proxy; + }); + utils.addProperty(chai.Assertion.prototype, "rejects", function __VITEST_REJECTS__() { + utils.flag(this, "promise", "rejects"); + utils.flag(this, "error", new Error("rejects")); + const obj = utils.flag(this, "object"); + const wrapper = typeof obj === "function" ? obj() : obj; + if (typeof (wrapper == null ? void 0 : wrapper.then) !== "function") + throw new TypeError(`You must provide a Promise to expect() when using .rejects, not '${typeof wrapper}'.`); + const proxy = new Proxy(this, { + get: (target, key, receiver) => { + const result = Reflect.get(target, key, receiver); + if (typeof result !== "function") + return result instanceof chai.Assertion ? proxy : result; + return async (...args) => { + return wrapper.then( + (value) => { + throw new Error(`promise resolved "${String(value)}" instead of rejecting`); + }, + (err) => { + utils.flag(this, "object", err); + return result.call(this, ...args); + } + ); + }; + } + }); + return proxy; + }); +}; +const isAsyncFunction = (fn) => typeof fn === "function" && fn[Symbol.toStringTag] === "AsyncFunction"; +const getMatcherState = (assertion, expect) => { + const obj = assertion._obj; + const isNot = util.flag(assertion, "negate"); + const promise = util.flag(assertion, "promise") || ""; + const jestUtils = { + ...matcherUtils, + iterableEquality, + subsetEquality + }; + const matcherState = { + ...getState(expect), + isNot, + utils: jestUtils, + promise, + equals, + suppressedErrors: [] + }; + return { + state: matcherState, + isNot, + obj + }; +}; +class JestExtendError extends Error { + constructor(message, actual, expected) { + super(message); + this.actual = actual; + this.expected = expected; + } +} +function JestExtendPlugin(expect, matchers) { + return (c2, utils) => { + Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => { + function expectSyncWrapper(...args) { + const { state, isNot, obj } = getMatcherState(this, expect); + const { pass, message, actual, expected } = expectAssertion.call(state, obj, ...args); + if (pass && isNot || !pass && !isNot) + throw new JestExtendError(message(), actual, expected); + } + async function expectAsyncWrapper(...args) { + const { state, isNot, obj } = getMatcherState(this, expect); + const { pass, message, actual, expected } = await expectAssertion.call(state, obj, ...args); + if (pass && isNot || !pass && !isNot) + throw new JestExtendError(message(), actual, expected); + } + const expectAssertionWrapper = isAsyncFunction(expectAssertion) ? expectAsyncWrapper : expectSyncWrapper; + utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, expectAssertionName, expectAssertionWrapper); + utils.addMethod(c2.Assertion.prototype, expectAssertionName, expectAssertionWrapper); + class CustomMatcher extends AsymmetricMatcher$1 { + constructor(inverse = false, ...sample) { + super(sample, inverse); + } + asymmetricMatch(other) { + const { pass } = expectAssertion.call( + this.getMatcherContext(expect), + other, + ...this.sample + ); + return this.inverse ? !pass : pass; + } + toString() { + return `${this.inverse ? "not." : ""}${expectAssertionName}`; + } + getExpectedType() { + return "any"; + } + toAsymmetricMatcher() { + return `${this.toString()}<${this.sample.map(String).join(", ")}>`; + } + } + Object.defineProperty(expect, expectAssertionName, { + configurable: true, + enumerable: true, + value: (...sample) => new CustomMatcher(false, ...sample), + writable: true + }); + Object.defineProperty(expect.not, expectAssertionName, { + configurable: true, + enumerable: true, + value: (...sample) => new CustomMatcher(true, ...sample), + writable: true + }); + }); + }; +} +const JestExtend = (chai, utils) => { + utils.addMethod(chai.expect, "extend", (expect, expects) => { + chai.use(JestExtendPlugin(expect, expects)); + }); +}; + +var naturalCompare$1 = {exports: {}}; + +/* + * @version 1.4.0 + * @date 2015-10-26 + * @stability 3 - Stable + * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite) + * @license MIT License + */ + + +var naturalCompare = function(a, b) { + var i, codeA + , codeB = 1 + , posA = 0 + , posB = 0 + , alphabet = String.alphabet; + + function getCode(str, pos, code) { + if (code) { + for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i; + return +str.slice(pos - 1, i) + } + code = alphabet && alphabet.indexOf(str.charAt(pos)); + return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code + : code < 46 ? 65 // - + : code < 48 ? code - 1 + : code < 58 ? code + 18 // 0-9 + : code < 65 ? code - 11 + : code < 91 ? code + 11 // A-Z + : code < 97 ? code - 37 + : code < 123 ? code + 5 // a-z + : code - 63 + } + + + if ((a+="") != (b+="")) for (;codeB;) { + codeA = getCode(a, posA++); + codeB = getCode(b, posB++); + + if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) { + codeA = getCode(a, posA, posA); + codeB = getCode(b, posB, posA = i); + posB = i; + } + + if (codeA != codeB) return (codeA < codeB) ? -1 : 1 + } + return 0 +}; + +try { + naturalCompare$1.exports = naturalCompare; +} catch (e) { + String.naturalCompare = naturalCompare; +} + +const serialize$1 = (val, config, indentation, depth, refs, printer) => { + const name = val.getMockName(); + const nameString = name === "vi.fn()" ? "" : ` ${name}`; + let callsString = ""; + if (val.mock.calls.length !== 0) { + const indentationNext = indentation + config.indent; + callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer(val.mock.calls, config, indentationNext, depth, refs)}${config.min ? ", " : ","}${config.spacingOuter}${indentationNext}"results": ${printer(val.mock.results, config, indentationNext, depth, refs)}${config.min ? "" : ","}${config.spacingOuter}${indentation}}`; + } + return `[MockFunction${nameString}]${callsString}`; +}; +const test$1 = (val) => val && !!val._isMockFunction; +const plugin = { serialize: serialize$1, test: test$1 }; + +const { + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent, + AsymmetricMatcher +} = plugins_1; +let PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher, + plugin +]; +const addSerializer = (plugin) => { + PLUGINS = [plugin].concat(PLUGINS); +}; +const getSerializers = () => PLUGINS; + +const SNAPSHOT_VERSION = "1"; +const writeSnapshotVersion = () => `// Vitest Snapshot v${SNAPSHOT_VERSION}`; +const testNameToKey = (testName, count) => `${testName} ${count}`; +const keyToTestName = (key) => { + if (!/ \d+$/.test(key)) + throw new Error("Snapshot keys must end with a number."); + return key.replace(/ \d+$/, ""); +}; +const getSnapshotData = (snapshotPath, update) => { + const data = /* @__PURE__ */ Object.create(null); + let snapshotContents = ""; + let dirty = false; + if (fs.existsSync(snapshotPath)) { + try { + snapshotContents = fs.readFileSync(snapshotPath, "utf8"); + const populate = new Function("exports", snapshotContents); + populate(data); + } catch { + } + } + const isInvalid = snapshotContents; + if ((update === "all" || update === "new") && isInvalid) + dirty = true; + return { data, dirty }; +}; +const addExtraLineBreaks = (string) => string.includes("\n") ? ` +${string} +` : string; +const removeExtraLineBreaks = (string) => string.length > 2 && string.startsWith("\n") && string.endsWith("\n") ? string.slice(1, -1) : string; +const escapeRegex = true; +const printFunctionName = false; +function serialize(val, indent = 2, formatOverrides = {}) { + return normalizeNewlines( + format_1(val, { + escapeRegex, + indent, + plugins: getSerializers(), + printFunctionName, + ...formatOverrides + }) + ); +} +function escapeBacktickString(str) { + return str.replace(/`|\\|\${/g, "\\$&"); +} +function printBacktickString(str) { + return `\`${escapeBacktickString(str)}\``; +} +function ensureDirectoryExists(filePath) { + try { + fs.mkdirSync(join(dirname(filePath)), { recursive: true }); + } catch { + } +} +function normalizeNewlines(string) { + return string.replace(/\r\n|\r/g, "\n"); +} +async function saveSnapshotFile(snapshotData, snapshotPath) { + var _a, _b; + const snapshots = Object.keys(snapshotData).sort(naturalCompare$1.exports).map( + (key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};` + ); + const content = `${writeSnapshotVersion()} + +${snapshots.join("\n\n")} +`; + const skipWriting = fs.existsSync(snapshotPath) && await ((_a = fs) == null ? void 0 : _a.promises.readFile(snapshotPath, "utf8")) === content; + if (skipWriting) + return; + ensureDirectoryExists(snapshotPath); + await ((_b = fs) == null ? void 0 : _b.promises.writeFile( + snapshotPath, + content, + "utf-8" + )); +} +function prepareExpected(expected) { + function findStartIndent() { + var _a, _b; + const matchObject = /^( +)}\s+$/m.exec(expected || ""); + const objectIndent = (_a = matchObject == null ? void 0 : matchObject[1]) == null ? void 0 : _a.length; + if (objectIndent) + return objectIndent; + const matchText = /^\n( +)"/.exec(expected || ""); + return ((_b = matchText == null ? void 0 : matchText[1]) == null ? void 0 : _b.length) || 0; + } + const startIndent = findStartIndent(); + let expectedTrimmed = expected == null ? void 0 : expected.trim(); + if (startIndent) { + expectedTrimmed = expectedTrimmed == null ? void 0 : expectedTrimmed.replace(new RegExp(`^${" ".repeat(startIndent)}`, "gm"), "").replace(/ +}$/, "}"); + } + return expectedTrimmed; +} +function deepMergeArray(target = [], source = []) { + const mergedOutput = Array.from(target); + source.forEach((sourceElement, index) => { + const targetElement = mergedOutput[index]; + if (Array.isArray(target[index])) { + mergedOutput[index] = deepMergeArray(target[index], sourceElement); + } else if (isObject$1(targetElement)) { + mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement); + } else { + mergedOutput[index] = sourceElement; + } + }); + return mergedOutput; +} +function deepMergeSnapshot(target, source) { + if (isObject$1(target) && isObject$1(source)) { + const mergedOutput = { ...target }; + Object.keys(source).forEach((key) => { + if (isObject$1(source[key]) && !source[key].$$typeof) { + if (!(key in target)) + Object.assign(mergedOutput, { [key]: source[key] }); + else + mergedOutput[key] = deepMergeSnapshot(target[key], source[key]); + } else if (Array.isArray(source[key])) { + mergedOutput[key] = deepMergeArray(target[key], source[key]); + } else { + Object.assign(mergedOutput, { [key]: source[key] }); + } + }); + return mergedOutput; + } else if (Array.isArray(target) && Array.isArray(source)) { + return deepMergeArray(target, source); + } + return target; +} + +async function saveInlineSnapshots(snapshots) { + const MagicString = (await import('./chunk-magic-string.3a794426.js')).default; + const files = new Set(snapshots.map((i) => i.file)); + await Promise.all(Array.from(files).map(async (file) => { + const snaps = snapshots.filter((i) => i.file === file); + const code = await promises.readFile(file, "utf8"); + const s = new MagicString(code); + for (const snap of snaps) { + const index = positionToOffset(code, snap.line, snap.column); + replaceInlineSnap(code, s, index, snap.snapshot); + } + const transformed = s.toString(); + if (transformed !== code) + await promises.writeFile(file, transformed, "utf-8"); + })); +} +const startObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\S\s]*\*\/\s*|\/\/.*\s+)*\s*({)/m; +function replaceObjectSnap(code, s, index, newSnap) { + code = code.slice(index); + const startMatch = startObjectRegex.exec(code); + if (!startMatch) + return false; + code = code.slice(startMatch.index); + const charIndex = getCallLastIndex(code); + if (charIndex === null) + return false; + s.appendLeft(index + startMatch.index + charIndex, `, ${prepareSnapString(newSnap, code, index)}`); + return true; +} +function prepareSnapString(snap, source, index) { + const lineNumber = offsetToLineNumber(source, index); + const line = source.split(lineSplitRE)[lineNumber - 1]; + const indent = line.match(/^\s*/)[0] || ""; + const indentNext = indent.includes(" ") ? `${indent} ` : `${indent} `; + const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g); + const isOneline = lines.length <= 1; + const quote = isOneline ? "'" : "`"; + if (isOneline) + return `'${lines.join("\n").replace(/'/g, "\\'")}'`; + else + return `${quote} +${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\${/g, "\\${")} +${indent}${quote}`; +} +const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\S\s]*\*\/\s*|\/\/.*\s+)*\s*[\w_$]*(['"`\)])/m; +function replaceInlineSnap(code, s, index, newSnap) { + const startMatch = startRegex.exec(code.slice(index)); + if (!startMatch) + return replaceObjectSnap(code, s, index, newSnap); + const quote = startMatch[1]; + const startIndex = index + startMatch.index + startMatch[0].length; + const snapString = prepareSnapString(newSnap, code, index); + if (quote === ")") { + s.appendRight(startIndex - 1, snapString); + return true; + } + const quoteEndRE = new RegExp(`(?:^|[^\\\\])${quote}`); + const endMatch = quoteEndRE.exec(code.slice(startIndex)); + if (!endMatch) + return false; + const endIndex = startIndex + endMatch.index + endMatch[0].length; + s.overwrite(startIndex - 1, endIndex, snapString); + return true; +} +const INDENTATION_REGEX = /^([^\S\n]*)\S/m; +function stripSnapshotIndentation(inlineSnapshot) { + const match = inlineSnapshot.match(INDENTATION_REGEX); + if (!match || !match[1]) { + return inlineSnapshot; + } + const indentation = match[1]; + const lines = inlineSnapshot.split(/\n/g); + if (lines.length <= 2) { + return inlineSnapshot; + } + if (lines[0].trim() !== "" || lines[lines.length - 1].trim() !== "") { + return inlineSnapshot; + } + for (let i = 1; i < lines.length - 1; i++) { + if (lines[i] !== "") { + if (lines[i].indexOf(indentation) !== 0) { + return inlineSnapshot; + } + lines[i] = lines[i].substring(indentation.length); + } + } + lines[lines.length - 1] = ""; + inlineSnapshot = lines.join("\n"); + return inlineSnapshot; +} + +class SnapshotState { + constructor(testFilePath, snapshotPath, options) { + this.testFilePath = testFilePath; + this.snapshotPath = snapshotPath; + const { data, dirty } = getSnapshotData( + this.snapshotPath, + options.updateSnapshot + ); + this._initialData = data; + this._snapshotData = data; + this._dirty = dirty; + this._inlineSnapshots = []; + this._uncheckedKeys = new Set(Object.keys(this._snapshotData)); + this._counters = /* @__PURE__ */ new Map(); + this.expand = options.expand || false; + this.added = 0; + this.matched = 0; + this.unmatched = 0; + this._updateSnapshot = options.updateSnapshot; + this.updated = 0; + this._snapshotFormat = { + printBasicPrototype: false, + ...options.snapshotFormat + }; + } + markSnapshotsAsCheckedForTest(testName) { + this._uncheckedKeys.forEach((uncheckedKey) => { + if (keyToTestName(uncheckedKey) === testName) + this._uncheckedKeys.delete(uncheckedKey); + }); + } + _inferInlineSnapshotStack(stacks) { + const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/)); + if (promiseIndex !== -1) + return stacks[promiseIndex + 3]; + const stackIndex = stacks.findIndex((i) => i.method.includes("__VITEST_INLINE_SNAPSHOT__")); + return stackIndex !== -1 ? stacks[stackIndex + 2] : null; + } + _addSnapshot(key, receivedSerialized, options) { + this._dirty = true; + if (options.isInline) { + const error = options.error || new Error("Unknown error"); + const stacks = parseStacktrace(error, true); + stacks.forEach((i) => i.file = slash(i.file)); + const stack = this._inferInlineSnapshotStack(stacks); + if (!stack) { + throw new Error( + `Vitest: Couldn't infer stack frame for inline snapshot. +${JSON.stringify(stacks)}` + ); + } + stack.column--; + this._inlineSnapshots.push({ + snapshot: receivedSerialized, + ...stack + }); + } else { + this._snapshotData[key] = receivedSerialized; + } + } + clear() { + this._snapshotData = this._initialData; + this._counters = /* @__PURE__ */ new Map(); + this.added = 0; + this.matched = 0; + this.unmatched = 0; + this.updated = 0; + this._dirty = false; + } + async save() { + const hasExternalSnapshots = Object.keys(this._snapshotData).length; + const hasInlineSnapshots = this._inlineSnapshots.length; + const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots; + const status = { + deleted: false, + saved: false + }; + if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) { + if (hasExternalSnapshots) + await saveSnapshotFile(this._snapshotData, this.snapshotPath); + if (hasInlineSnapshots) + await saveInlineSnapshots(this._inlineSnapshots); + status.saved = true; + } else if (!hasExternalSnapshots && fs.existsSync(this.snapshotPath)) { + if (this._updateSnapshot === "all") + fs.unlinkSync(this.snapshotPath); + status.deleted = true; + } + return status; + } + getUncheckedCount() { + return this._uncheckedKeys.size || 0; + } + getUncheckedKeys() { + return Array.from(this._uncheckedKeys); + } + removeUncheckedKeys() { + if (this._updateSnapshot === "all" && this._uncheckedKeys.size) { + this._dirty = true; + this._uncheckedKeys.forEach((key) => delete this._snapshotData[key]); + this._uncheckedKeys.clear(); + } + } + match({ + testName, + received, + key, + inlineSnapshot, + isInline, + error + }) { + this._counters.set(testName, (this._counters.get(testName) || 0) + 1); + const count = Number(this._counters.get(testName)); + if (!key) + key = testNameToKey(testName, count); + if (!(isInline && this._snapshotData[key] !== void 0)) + this._uncheckedKeys.delete(key); + const receivedSerialized = addExtraLineBreaks(serialize(received, void 0, this._snapshotFormat)); + const expected = isInline ? inlineSnapshot : this._snapshotData[key]; + const expectedTrimmed = prepareExpected(expected); + const pass = expectedTrimmed === prepareExpected(receivedSerialized); + const hasSnapshot = expected !== void 0; + const snapshotIsPersisted = isInline || fs.existsSync(this.snapshotPath); + if (pass && !isInline) { + this._snapshotData[key] = receivedSerialized; + } + if (hasSnapshot && this._updateSnapshot === "all" || (!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all")) { + if (this._updateSnapshot === "all") { + if (!pass) { + if (hasSnapshot) + this.updated++; + else + this.added++; + this._addSnapshot(key, receivedSerialized, { error, isInline }); + } else { + this.matched++; + } + } else { + this._addSnapshot(key, receivedSerialized, { error, isInline }); + this.added++; + } + return { + actual: "", + count, + expected: "", + key, + pass: true + }; + } else { + if (!pass) { + this.unmatched++; + return { + actual: removeExtraLineBreaks(receivedSerialized), + count, + expected: expectedTrimmed !== void 0 ? removeExtraLineBreaks(expectedTrimmed) : void 0, + key, + pass: false + }; + } else { + this.matched++; + return { + actual: "", + count, + expected: "", + key, + pass: true + }; + } + } + } + async pack() { + const snapshot = { + filepath: this.testFilePath, + added: 0, + fileDeleted: false, + matched: 0, + unchecked: 0, + uncheckedKeys: [], + unmatched: 0, + updated: 0 + }; + const uncheckedCount = this.getUncheckedCount(); + const uncheckedKeys = this.getUncheckedKeys(); + if (uncheckedCount) + this.removeUncheckedKeys(); + const status = await this.save(); + snapshot.fileDeleted = status.deleted; + snapshot.added = this.added; + snapshot.matched = this.matched; + snapshot.unmatched = this.unmatched; + snapshot.updated = this.updated; + snapshot.unchecked = !status.deleted ? uncheckedCount : 0; + snapshot.uncheckedKeys = Array.from(uncheckedKeys); + return snapshot; + } +} + +class SnapshotClient { + constructor() { + this.snapshotStateMap = /* @__PURE__ */ new Map(); + } + async setTest(test) { + var _a; + this.test = test; + if (((_a = this.snapshotState) == null ? void 0 : _a.testFilePath) !== this.test.file.filepath) { + this.saveCurrent(); + const filePath = this.test.file.filepath; + if (!this.getSnapshotState(test)) { + this.snapshotStateMap.set( + filePath, + new SnapshotState( + filePath, + await rpc().resolveSnapshotPath(filePath), + getWorkerState().config.snapshotOptions + ) + ); + } + this.snapshotState = this.getSnapshotState(test); + } + } + getSnapshotState(test) { + return this.snapshotStateMap.get(test.file.filepath); + } + clearTest() { + this.test = void 0; + } + skipTestSnapshots(test) { + var _a; + (_a = this.snapshotState) == null ? void 0 : _a.markSnapshotsAsCheckedForTest(test.name); + } + assert(options) { + const { + test = this.test, + message, + isInline = false, + properties, + inlineSnapshot, + error, + errorMessage + } = options; + let { received } = options; + if (!test) + throw new Error("Snapshot cannot be used outside of test"); + if (typeof properties === "object") { + if (typeof received !== "object" || !received) + throw new Error("Received value must be an object when the matcher has properties"); + try { + const pass2 = equals(received, properties, [iterableEquality, subsetEquality]); + if (!pass2) + expect(received).equals(properties); + else + received = deepMergeSnapshot(received, properties); + } catch (err) { + err.message = errorMessage || "Snapshot mismatched"; + throw err; + } + } + const testName = [ + ...getNames(test).slice(1), + ...message ? [message] : [] + ].join(" > "); + const snapshotState = this.getSnapshotState(test); + const { actual, expected, key, pass } = snapshotState.match({ + testName, + received, + isInline, + error, + inlineSnapshot + }); + if (!pass) { + try { + expect(actual.trim()).equals(expected ? expected.trim() : ""); + } catch (error2) { + error2.message = errorMessage || `Snapshot \`${key || "unknown"}\` mismatched`; + throw error2; + } + } + } + async saveCurrent() { + if (!this.snapshotState) + return; + const result = await this.snapshotState.pack(); + await rpc().snapshotSaved(result); + this.snapshotState = void 0; + } + clear() { + this.snapshotStateMap.clear(); + } +} + +let _client; +function getSnapshotClient() { + if (!_client) + _client = new SnapshotClient(); + return _client; +} +const getErrorMessage = (err) => { + if (err instanceof Error) + return err.message; + return err; +}; +const getErrorString = (expected, promise) => { + if (typeof expected !== "function") { + if (!promise) + throw new Error(`expected must be a function, received ${typeof expected}`); + return getErrorMessage(expected); + } + try { + expected(); + } catch (e) { + return getErrorMessage(e); + } + throw new Error("snapshot function didn't throw"); +}; +const SnapshotPlugin = (chai, utils) => { + for (const key of ["matchSnapshot", "toMatchSnapshot"]) { + utils.addMethod( + chai.Assertion.prototype, + key, + function(properties, message) { + const expected = utils.flag(this, "object"); + const test = utils.flag(this, "vitest-test"); + if (typeof properties === "string" && typeof message === "undefined") { + message = properties; + properties = void 0; + } + const errorMessage = utils.flag(this, "message"); + getSnapshotClient().assert({ + received: expected, + test, + message, + isInline: false, + properties, + errorMessage + }); + } + ); + } + utils.addMethod( + chai.Assertion.prototype, + "toMatchInlineSnapshot", + function __VITEST_INLINE_SNAPSHOT__(properties, inlineSnapshot, message) { + const expected = utils.flag(this, "object"); + const error = utils.flag(this, "error"); + const test = utils.flag(this, "vitest-test"); + if (typeof properties === "string") { + message = inlineSnapshot; + inlineSnapshot = properties; + properties = void 0; + } + if (inlineSnapshot) + inlineSnapshot = stripSnapshotIndentation(inlineSnapshot); + const errorMessage = utils.flag(this, "message"); + getSnapshotClient().assert({ + received: expected, + test, + message, + isInline: true, + properties, + inlineSnapshot, + error, + errorMessage + }); + } + ); + utils.addMethod( + chai.Assertion.prototype, + "toThrowErrorMatchingSnapshot", + function(message) { + const expected = utils.flag(this, "object"); + const test = utils.flag(this, "vitest-test"); + const promise = utils.flag(this, "promise"); + const errorMessage = utils.flag(this, "message"); + getSnapshotClient().assert({ + received: getErrorString(expected, promise), + test, + message, + errorMessage + }); + } + ); + utils.addMethod( + chai.Assertion.prototype, + "toThrowErrorMatchingInlineSnapshot", + function __VITEST_INLINE_SNAPSHOT__(inlineSnapshot, message) { + const expected = utils.flag(this, "object"); + const error = utils.flag(this, "error"); + const test = utils.flag(this, "vitest-test"); + const promise = utils.flag(this, "promise"); + const errorMessage = utils.flag(this, "message"); + getSnapshotClient().assert({ + received: getErrorString(expected, promise), + test, + message, + inlineSnapshot, + isInline: true, + error, + errorMessage + }); + } + ); + utils.addMethod( + chai.expect, + "addSnapshotSerializer", + addSerializer + ); +}; + +var chai$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + getSnapshotClient: getSnapshotClient, + SnapshotPlugin: SnapshotPlugin +}); + +chai$2.use(JestExtend); +chai$2.use(JestChaiExpect); +chai$2.use(Subset); +chai$2.use(SnapshotPlugin); +chai$2.use(JestAsymmetricMatchers); + +function createExpect(test) { + var _a; + const expect = (value, message) => { + const { assertionCalls } = getState(expect); + setState({ assertionCalls: assertionCalls + 1 }, expect); + const assert2 = chai$2.expect(value, message); + if (test) + return assert2.withTest(test); + else + return assert2; + }; + Object.assign(expect, chai$2.expect); + expect.getState = () => getState(expect); + expect.setState = (state) => setState(state, expect); + const globalState = getState(globalThis[GLOBAL_EXPECT]) || {}; + setState({ + ...globalState, + assertionCalls: 0, + isExpectingAssertions: false, + isExpectingAssertionsError: null, + expectedAssertionsNumber: null, + expectedAssertionsNumberErrorGen: null, + environment: getCurrentEnvironment(), + testPath: test ? (_a = test.suite.file) == null ? void 0 : _a.filepath : globalState.testPath, + currentTestName: test ? getFullName(test) : globalState.currentTestName + }, expect); + expect.extend = (matchers) => chai$2.expect.extend(expect, matchers); + function assertions(expected) { + const errorGen = () => new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`); + if (Error.captureStackTrace) + Error.captureStackTrace(errorGen(), assertions); + expect.setState({ + expectedAssertionsNumber: expected, + expectedAssertionsNumberErrorGen: errorGen + }); + } + function hasAssertions() { + const error = new Error("expected any number of assertion, but got none"); + if (Error.captureStackTrace) + Error.captureStackTrace(error, hasAssertions); + expect.setState({ + isExpectingAssertions: true, + isExpectingAssertionsError: error + }); + } + chai$2.util.addMethod(expect, "assertions", assertions); + chai$2.util.addMethod(expect, "hasAssertions", hasAssertions); + return expect; +} +const globalExpect = createExpect(); +Object.defineProperty(globalThis, GLOBAL_EXPECT, { + value: globalExpect, + writable: true, + configurable: true +}); + +const collectorContext = { + tasks: [], + currentSuite: null +}; +function collectTask(task) { + var _a; + (_a = collectorContext.currentSuite) == null ? void 0 : _a.tasks.push(task); +} +async function runWithSuite(suite, fn) { + const prev = collectorContext.currentSuite; + collectorContext.currentSuite = suite; + await fn(); + collectorContext.currentSuite = prev; +} +function getDefaultTestTimeout() { + return getWorkerState().config.testTimeout; +} +function getDefaultHookTimeout() { + return getWorkerState().config.hookTimeout; +} +function withTimeout(fn, timeout = getDefaultTestTimeout(), isHook = false) { + if (timeout <= 0 || timeout === Infinity) + return fn; + return (...args) => { + return Promise.race([fn(...args), new Promise((resolve, reject) => { + var _a; + const timer = safeSetTimeout(() => { + safeClearTimeout(timer); + reject(new Error(makeTimeoutMsg(isHook, timeout))); + }, timeout); + (_a = timer.unref) == null ? void 0 : _a.call(timer); + })]); + }; +} +function createTestContext(test) { + const context = function() { + throw new Error("done() callback is deprecated, use promise instead"); + }; + context.meta = test; + let _expect; + Object.defineProperty(context, "expect", { + get() { + if (!_expect) + _expect = createExpect(test); + return _expect; + } + }); + Object.defineProperty(context, "_local", { + get() { + return _expect != null; + } + }); + context.onTestFailed = (fn) => { + test.onFailed || (test.onFailed = []); + test.onFailed.push(fn); + }; + return context; +} +function makeTimeoutMsg(isHook, timeout) { + return `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms. +If this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`; +} + +const fnMap = /* @__PURE__ */ new WeakMap(); +const hooksMap = /* @__PURE__ */ new WeakMap(); +const benchOptsMap = /* @__PURE__ */ new WeakMap(); +function setFn(key, fn) { + fnMap.set(key, fn); +} +function getFn(key) { + return fnMap.get(key); +} +function setHooks(key, hooks) { + hooksMap.set(key, hooks); +} +function getHooks(key) { + return hooksMap.get(key); +} +function setBenchOptions(key, val) { + benchOptsMap.set(key, val); +} +function getBenchOptions(key) { + return benchOptsMap.get(key); +} + +const suite = createSuite(); +const test = createTest( + function(name, fn, options) { + getCurrentSuite().test.fn.call(this, name, fn, options); + } +); +const bench = createBenchmark( + function(name, fn = noop, options = {}) { + getCurrentSuite().benchmark.fn.call(this, name, fn, options); + } +); +const describe = suite; +const it = test; +const workerState = getWorkerState(); +const defaultSuite = workerState.config.sequence.shuffle ? suite.shuffle("") : suite(""); +function clearCollectorContext() { + collectorContext.tasks.length = 0; + defaultSuite.clear(); + collectorContext.currentSuite = defaultSuite; +} +function getCurrentSuite() { + return collectorContext.currentSuite || defaultSuite; +} +function createSuiteHooks() { + return { + beforeAll: [], + afterAll: [], + beforeEach: [], + afterEach: [] + }; +} +function createSuiteCollector(name, factory = () => { +}, mode, concurrent, shuffle, suiteOptions) { + const tasks = []; + const factoryQueue = []; + let suite2; + initSuite(); + const test2 = createTest(function(name2, fn = noop, options = suiteOptions) { + if (!isRunningInTest()) + throw new Error("`test()` and `it()` is only available in test mode."); + const mode2 = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run"; + if (typeof options === "number") + options = { timeout: options }; + const test3 = { + id: "", + type: "test", + name: name2, + mode: mode2, + suite: void 0, + fails: this.fails, + retry: options == null ? void 0 : options.retry + }; + if (this.concurrent || concurrent) + test3.concurrent = true; + if (shuffle) + test3.shuffle = true; + const context = createTestContext(test3); + Object.defineProperty(test3, "context", { + value: context, + enumerable: false + }); + setFn(test3, withTimeout( + () => fn(context), + options == null ? void 0 : options.timeout + )); + tasks.push(test3); + }); + const benchmark = createBenchmark(function(name2, fn = noop, options = {}) { + const mode2 = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run"; + if (!isRunningInBenchmark()) + throw new Error("`bench()` is only available in benchmark mode. Run with `vitest bench` instead."); + const benchmark2 = { + type: "benchmark", + id: "", + name: name2, + mode: mode2, + suite: void 0 + }; + setFn(benchmark2, fn); + setBenchOptions(benchmark2, options); + tasks.push(benchmark2); + }); + const collector = { + type: "collector", + name, + mode, + test: test2, + tasks, + benchmark, + collect, + clear, + on: addHook + }; + function addHook(name2, ...fn) { + getHooks(suite2)[name2].push(...fn); + } + function initSuite() { + suite2 = { + id: "", + type: "suite", + name, + mode, + shuffle, + tasks: [] + }; + setHooks(suite2, createSuiteHooks()); + } + function clear() { + tasks.length = 0; + factoryQueue.length = 0; + initSuite(); + } + async function collect(file) { + factoryQueue.length = 0; + if (factory) + await runWithSuite(collector, () => factory(test2)); + const allChildren = []; + for (const i of [...factoryQueue, ...tasks]) + allChildren.push(i.type === "collector" ? await i.collect(file) : i); + suite2.file = file; + suite2.tasks = allChildren; + allChildren.forEach((task) => { + task.suite = suite2; + if (file) + task.file = file; + }); + return suite2; + } + collectTask(collector); + return collector; +} +function createSuite() { + function suiteFn(name, factory, options) { + const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run"; + return createSuiteCollector(name, factory, mode, this.concurrent, this.shuffle, options); + } + suiteFn.each = function(cases, ...args) { + const suite2 = this.withContext(); + if (Array.isArray(cases) && args.length) + cases = formatTemplateString(cases, args); + return (name, fn, options) => { + const arrayOnlyCases = cases.every(Array.isArray); + cases.forEach((i, idx) => { + const items = Array.isArray(i) ? i : [i]; + arrayOnlyCases ? suite2(formatTitle(name, items, idx), () => fn(...items), options) : suite2(formatTitle(name, items, idx), () => fn(i), options); + }); + }; + }; + suiteFn.skipIf = (condition) => condition ? suite.skip : suite; + suiteFn.runIf = (condition) => condition ? suite : suite.skip; + return createChainable( + ["concurrent", "shuffle", "skip", "only", "todo"], + suiteFn + ); +} +function createTest(fn) { + const testFn = fn; + testFn.each = function(cases, ...args) { + const test2 = this.withContext(); + if (Array.isArray(cases) && args.length) + cases = formatTemplateString(cases, args); + return (name, fn2, options) => { + const arrayOnlyCases = cases.every(Array.isArray); + cases.forEach((i, idx) => { + const items = Array.isArray(i) ? i : [i]; + arrayOnlyCases ? test2(formatTitle(name, items, idx), () => fn2(...items), options) : test2(formatTitle(name, items, idx), () => fn2(i), options); + }); + }; + }; + testFn.skipIf = (condition) => condition ? test.skip : test; + testFn.runIf = (condition) => condition ? test : test.skip; + return createChainable( + ["concurrent", "skip", "only", "todo", "fails"], + testFn + ); +} +function createBenchmark(fn) { + const benchmark = createChainable( + ["skip", "only", "todo"], + fn + ); + benchmark.skipIf = (condition) => condition ? benchmark.skip : benchmark; + benchmark.runIf = (condition) => condition ? benchmark : benchmark.skip; + return benchmark; +} +function formatTitle(template, items, idx) { + if (template.includes("%#")) { + template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/__vitest_escaped_%__/g, "%%"); + } + const count = template.split("%").length - 1; + let formatted = util$1.format(template, ...items.slice(0, count)); + if (isObject$1(items[0])) { + formatted = formatted.replace( + /\$([$\w_.]+)/g, + (_, key) => util.objDisplay(objectAttr(items[0], key)) + ); + } + return formatted; +} +function formatTemplateString(cases, args) { + const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0]; + const res = []; + for (let i = 0; i < Math.floor(args.length / header.length); i++) { + const oneCase = {}; + for (let j = 0; j < header.length; j++) + oneCase[header[j]] = args[i * header.length + j]; + res.push(oneCase); + } + return res; +} + +export { GLOBAL_EXPECT as G, getDefaultHookTimeout as a, bench as b, createExpect as c, describe as d, globalExpect as e, clearCollectorContext as f, getCurrentSuite as g, defaultSuite as h, it as i, setHooks as j, getHooks as k, collectorContext as l, getBenchOptions as m, getFn as n, setState as o, getSnapshotClient as p, getState as q, createSuiteHooks as r, suite as s, test as t, chai$1 as u, withTimeout as w }; diff --git a/node_modules/vitest/dist/chunk-runtime-error.fad2c32b.js b/node_modules/vitest/dist/chunk-runtime-error.fad2c32b.js new file mode 100644 index 0000000..16b6f87 --- /dev/null +++ b/node_modules/vitest/dist/chunk-runtime-error.fad2c32b.js @@ -0,0 +1,144 @@ +import util$1 from 'util'; +import { util } from 'chai'; +import { a as stringify } from './chunk-utils-timers.52534f96.js'; +import { w as deepClone, g as getWorkerState, x as getType } from './chunk-mock-date.a1c85759.js'; + +const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@"; +const IS_COLLECTION_SYMBOL = "@@__IMMUTABLE_ITERABLE__@@"; +const isImmutable = (v) => v && (v[IS_COLLECTION_SYMBOL] || v[IS_RECORD_SYMBOL]); +const OBJECT_PROTO = Object.getPrototypeOf({}); +function getUnserializableMessage(err) { + if (err instanceof Error) + return `: ${err.message}`; + if (typeof err === "string") + return `: ${err}`; + return ""; +} +function serializeError(val, seen = /* @__PURE__ */ new WeakMap()) { + if (!val || typeof val === "string") + return val; + if (typeof val === "function") + return `Function<${val.name || "anonymous"}>`; + if (typeof val === "symbol") + return val.toString(); + if (typeof val !== "object") + return val; + if (isImmutable(val)) + return serializeError(val.toJSON(), seen); + if (val instanceof Promise || val.constructor && val.constructor.prototype === "AsyncFunction") + return "Promise"; + if (typeof Element !== "undefined" && val instanceof Element) + return val.tagName; + if (typeof val.asymmetricMatch === "function") + return `${val.toString()} ${util$1.format(val.sample)}`; + if (seen.has(val)) + return seen.get(val); + if (Array.isArray(val)) { + const clone = new Array(val.length); + seen.set(val, clone); + val.forEach((e, i) => { + try { + clone[i] = serializeError(e, seen); + } catch (err) { + clone[i] = getUnserializableMessage(err); + } + }); + return clone; + } else { + const clone = /* @__PURE__ */ Object.create(null); + seen.set(val, clone); + let obj = val; + while (obj && obj !== OBJECT_PROTO) { + Object.getOwnPropertyNames(obj).forEach((key) => { + if (key in clone) + return; + try { + clone[key] = serializeError(val[key], seen); + } catch (err) { + delete clone[key]; + clone[key] = getUnserializableMessage(err); + } + }); + obj = Object.getPrototypeOf(obj); + } + return clone; + } +} +function normalizeErrorMessage(message) { + return message.replace(/__vite_ssr_import_\d+__\./g, ""); +} +function processError(err) { + if (!err || typeof err !== "object") + return err; + if (err.stack) + err.stackStr = String(err.stack); + if (err.name) + err.nameStr = String(err.name); + const clonedActual = deepClone(err.actual); + const clonedExpected = deepClone(err.expected); + const { replacedActual, replacedExpected } = replaceAsymmetricMatcher(clonedActual, clonedExpected); + err.actual = replacedActual; + err.expected = replacedExpected; + const workerState = getWorkerState(); + const maxDiffSize = workerState.config.outputDiffMaxSize; + if (typeof err.expected !== "string") + err.expected = stringify(err.expected, 10, { maxLength: maxDiffSize }); + if (typeof err.actual !== "string") + err.actual = stringify(err.actual, 10, { maxLength: maxDiffSize }); + try { + if (typeof err.message === "string") + err.message = normalizeErrorMessage(err.message); + if (typeof err.cause === "object" && typeof err.cause.message === "string") + err.cause.message = normalizeErrorMessage(err.cause.message); + } catch { + } + try { + return serializeError(err); + } catch (e) { + return serializeError(new Error(`Failed to fully serialize error: ${e == null ? void 0 : e.message} +Inner error message: ${err == null ? void 0 : err.message}`)); + } +} +function isAsymmetricMatcher(data) { + const type = getType(data); + return type === "Object" && typeof data.asymmetricMatch === "function"; +} +function isReplaceable(obj1, obj2) { + const obj1Type = getType(obj1); + const obj2Type = getType(obj2); + return obj1Type === obj2Type && obj1Type === "Object"; +} +function replaceAsymmetricMatcher(actual, expected, actualReplaced = /* @__PURE__ */ new WeakSet(), expectedReplaced = /* @__PURE__ */ new WeakSet()) { + if (!isReplaceable(actual, expected)) + return { replacedActual: actual, replacedExpected: expected }; + if (actualReplaced.has(actual) || expectedReplaced.has(expected)) + return { replacedActual: actual, replacedExpected: expected }; + actualReplaced.add(actual); + expectedReplaced.add(expected); + util.getOwnEnumerableProperties(expected).forEach((key) => { + const expectedValue = expected[key]; + const actualValue = actual[key]; + if (isAsymmetricMatcher(expectedValue)) { + if (expectedValue.asymmetricMatch(actualValue)) + actual[key] = expectedValue; + } else if (isAsymmetricMatcher(actualValue)) { + if (actualValue.asymmetricMatch(expectedValue)) + expected[key] = actualValue; + } else if (isReplaceable(actualValue, expectedValue)) { + const replaced = replaceAsymmetricMatcher( + actualValue, + expectedValue, + actualReplaced, + expectedReplaced + ); + actual[key] = replaced.replacedActual; + expected[key] = replaced.replacedExpected; + } + }); + return { + replacedActual: actual, + replacedExpected: expected + }; +} + +export { processError as p }; diff --git a/node_modules/vitest/dist/chunk-runtime-mocker.a677dd28.js b/node_modules/vitest/dist/chunk-runtime-mocker.a677dd28.js new file mode 100644 index 0000000..b2921ce --- /dev/null +++ b/node_modules/vitest/dist/chunk-runtime-mocker.a677dd28.js @@ -0,0 +1,348 @@ +import { ViteNodeRunner } from 'vite-node/client'; +import { isInternalRequest } from 'vite-node/utils'; +import { normalizePath } from 'vite'; +import { i as isNodeBuiltin } from './vendor-index.2e96c50b.js'; +import { g as getWorkerState, x as getType, H as getAllMockableProperties, d as getCurrentEnvironment } from './chunk-mock-date.a1c85759.js'; +import { existsSync, readdirSync } from 'node:fs'; +import { b as resolve, f as distDir, h as isAbsolute, d as dirname, j as join, c as basename, e as extname } from './chunk-utils-env.b861e3a0.js'; +import c from 'picocolors'; + +class RefTracker { + constructor() { + this.idMap = /* @__PURE__ */ new Map(); + this.mockedValueMap = /* @__PURE__ */ new Map(); + } + getId(value) { + return this.idMap.get(value); + } + getMockedValue(id) { + return this.mockedValueMap.get(id); + } + track(originalValue, mockedValue) { + const newId = this.idMap.size; + this.idMap.set(originalValue, newId); + this.mockedValueMap.set(newId, mockedValue); + return newId; + } +} +function isSpecialProp(prop, parentType) { + return parentType.includes("Function") && typeof prop === "string" && ["arguments", "callee", "caller", "length", "name"].includes(prop); +} +const _VitestMocker = class { + constructor(runner) { + this.runner = runner; + this.resolveCache = /* @__PURE__ */ new Map(); + } + get root() { + return this.runner.options.root; + } + get base() { + return this.runner.options.base; + } + get mockMap() { + return this.runner.options.mockMap; + } + get moduleCache() { + return this.runner.moduleCache; + } + getSuiteFilepath() { + return getWorkerState().filepath || "global"; + } + getMocks() { + const suite = this.getSuiteFilepath(); + const suiteMocks = this.mockMap.get(suite); + const globalMocks = this.mockMap.get("global"); + return { + ...globalMocks, + ...suiteMocks + }; + } + async resolvePath(rawId, importer) { + const [id, fsPath] = await this.runner.resolveUrl(rawId, importer); + const external = !isAbsolute(fsPath) || fsPath.includes("/node_modules/") ? rawId : null; + return { + id, + fsPath, + external + }; + } + async resolveMocks() { + await Promise.all(_VitestMocker.pendingIds.map(async (mock) => { + const { fsPath, external } = await this.resolvePath(mock.id, mock.importer); + if (mock.type === "unmock") + this.unmockPath(fsPath); + if (mock.type === "mock") + this.mockPath(mock.id, fsPath, external, mock.factory); + })); + _VitestMocker.pendingIds = []; + } + async callFunctionMock(dep, mock) { + var _a, _b; + const cached = (_a = this.moduleCache.get(dep)) == null ? void 0 : _a.exports; + if (cached) + return cached; + let exports; + try { + exports = await mock(); + } catch (err) { + const vitestError = new Error( + '[vitest] There was an error, when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/#vi-mock' + ); + vitestError.cause = err; + throw vitestError; + } + const filepath = dep.slice(5); + const mockpath = ((_b = this.resolveCache.get(this.getSuiteFilepath())) == null ? void 0 : _b[filepath]) || filepath; + if (exports === null || typeof exports !== "object") + throw new Error(`[vitest] vi.mock("${mockpath}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`); + const moduleExports = new Proxy(exports, { + get(target, prop) { + const val = target[prop]; + if (prop === "then") { + if (target instanceof Promise) + return target.then.bind(target); + } else if (!(prop in target)) { + throw new Error( + `[vitest] No "${String(prop)}" export is defined on the "${mockpath}" mock. Did you forget to return it from "vi.mock"? +If you need to partially mock a module, you can use "vi.importActual" inside: + +${c.green(`vi.mock("${mockpath}", async () => { + const actual = await vi.importActual("${mockpath}") + return { + ...actual, + // your mocked methods + }, +})`)} +` + ); + } + return val; + } + }); + this.moduleCache.set(dep, { exports: moduleExports }); + return moduleExports; + } + getMockPath(dep) { + return `mock:${dep}`; + } + getDependencyMock(id) { + return this.getMocks()[id]; + } + normalizePath(path) { + return this.moduleCache.normalizePath(path); + } + resolveMockPath(mockPath, external) { + const path = external || mockPath; + if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) { + const mockDirname = dirname(path); + const mockFolder = join(this.root, "__mocks__", mockDirname); + if (!existsSync(mockFolder)) + return null; + const files = readdirSync(mockFolder); + const baseOriginal = basename(path); + for (const file of files) { + const baseFile = basename(file, extname(file)); + if (baseFile === baseOriginal) + return resolve(mockFolder, file); + } + return null; + } + const dir = dirname(path); + const baseId = basename(path); + const fullPath = resolve(dir, "__mocks__", baseId); + return existsSync(fullPath) ? fullPath : null; + } + mockObject(object, mockExports = {}) { + if (!_VitestMocker.spyModule) { + throw new Error( + "Error: Spy module is not defined. This is likely an internal bug in Vitest. Please report it to https://github.com/vitest-dev/vitest/issues" + ); + } + const spyModule = _VitestMocker.spyModule; + const finalizers = new Array(); + const refs = new RefTracker(); + const define = (container, key, value) => { + try { + container[key] = value; + return true; + } catch { + return false; + } + }; + const mockPropertiesOf = (container, newContainer) => { + const containerType = getType(container); + const isModule = containerType === "Module" || !!container.__esModule; + for (const { key: property, descriptor } of getAllMockableProperties(container)) { + if (!isModule && descriptor.get) { + try { + Object.defineProperty(newContainer, property, descriptor); + } catch (error) { + } + continue; + } + if (isSpecialProp(property, containerType)) + continue; + const value = container[property]; + const refId = refs.getId(value); + if (refId !== void 0) { + finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId))); + continue; + } + const type = getType(value); + if (Array.isArray(value)) { + define(newContainer, property, []); + continue; + } + const isFunction = type.includes("Function") && typeof value === "function"; + if ((!isFunction || value.__isMockFunction) && type !== "Object" && type !== "Module") { + define(newContainer, property, value); + continue; + } + if (!define(newContainer, property, isFunction ? value : {})) + continue; + if (isFunction) { + spyModule.spyOn(newContainer, property).mockImplementation(() => void 0); + Object.defineProperty(newContainer[property], "length", { value: 0 }); + } + refs.track(value, newContainer[property]); + mockPropertiesOf(value, newContainer[property]); + } + }; + const mockedObject = mockExports; + mockPropertiesOf(object, mockedObject); + for (const finalizer of finalizers) + finalizer(); + return mockedObject; + } + unmockPath(path) { + const suitefile = this.getSuiteFilepath(); + const id = this.normalizePath(path); + const mock = this.mockMap.get(suitefile); + if (mock && id in mock) + delete mock[id]; + const mockId = this.getMockPath(id); + if (this.moduleCache.get(mockId)) + this.moduleCache.delete(mockId); + } + mockPath(originalId, path, external, factory) { + const suitefile = this.getSuiteFilepath(); + const id = this.normalizePath(path); + const mocks = this.mockMap.get(suitefile) || {}; + const resolves = this.resolveCache.get(suitefile) || {}; + mocks[id] = factory || this.resolveMockPath(path, external); + resolves[id] = originalId; + this.mockMap.set(suitefile, mocks); + this.resolveCache.set(suitefile, resolves); + } + async importActual(rawId, importee) { + const { id, fsPath } = await this.resolvePath(rawId, importee); + const result = await this.runner.cachedRequest(id, fsPath, [importee]); + return result; + } + async importMock(rawId, importee) { + const { id, fsPath, external } = await this.resolvePath(rawId, importee); + const normalizedId = this.normalizePath(fsPath); + let mock = this.getDependencyMock(normalizedId); + if (mock === void 0) + mock = this.resolveMockPath(fsPath, external); + if (mock === null) { + const mod = await this.runner.cachedRequest(id, fsPath, [importee]); + return this.mockObject(mod); + } + if (typeof mock === "function") + return this.callFunctionMock(fsPath, mock); + return this.runner.dependencyRequest(mock, mock, [importee]); + } + async initializeSpyModule() { + if (_VitestMocker.spyModule) + return; + _VitestMocker.spyModule = await this.runner.executeId(_VitestMocker.spyModulePath); + } + async requestWithMock(url, callstack) { + if (_VitestMocker.pendingIds.length) + await this.resolveMocks(); + const id = this.normalizePath(url); + const mock = this.getDependencyMock(id); + const mockPath = this.getMockPath(id); + if (mock === null) { + const cache = this.moduleCache.get(mockPath); + if (cache.exports) + return cache.exports; + const exports = {}; + this.moduleCache.set(mockPath, { exports }); + const mod = await this.runner.directRequest(url, url, callstack); + this.mockObject(mod, exports); + return exports; + } + if (typeof mock === "function" && !callstack.includes(mockPath) && !callstack.includes(url)) { + callstack.push(mockPath); + const result = await this.callFunctionMock(mockPath, mock); + const indexMock = callstack.indexOf(mockPath); + callstack.splice(indexMock, 1); + return result; + } + if (typeof mock === "string" && !callstack.includes(mock)) + return mock; + } + queueMock(id, importer, factory) { + _VitestMocker.pendingIds.push({ type: "mock", id, importer, factory }); + } + queueUnmock(id, importer) { + _VitestMocker.pendingIds.push({ type: "unmock", id, importer }); + } +}; +let VitestMocker = _VitestMocker; +VitestMocker.pendingIds = []; +VitestMocker.spyModulePath = resolve(distDir, "spy.js"); + +async function executeInViteNode(options) { + const runner = new VitestRunner(options); + await runner.executeId("/@vite/env"); + await runner.mocker.initializeSpyModule(); + const result = []; + for (const file of options.files) + result.push(await runner.executeFile(file)); + return result; +} +class VitestRunner extends ViteNodeRunner { + constructor(options) { + super(options); + this.options = options; + this.mocker = new VitestMocker(this); + } + shouldResolveId(id, _importee) { + if (isInternalRequest(id)) + return false; + const environment = getCurrentEnvironment(); + return environment === "node" ? !isNodeBuiltin(id) : true; + } + async resolveUrl(id, importee) { + if (importee && importee.startsWith("mock:")) + importee = importee.slice(5); + return super.resolveUrl(id, importee); + } + async dependencyRequest(id, fsPath, callstack) { + const mocked = await this.mocker.requestWithMock(fsPath, callstack); + if (typeof mocked === "string") + return super.dependencyRequest(mocked, mocked, callstack); + if (mocked && typeof mocked === "object") + return mocked; + return super.dependencyRequest(id, fsPath, callstack); + } + prepareContext(context) { + const workerState = getWorkerState(); + if (workerState.filepath && normalizePath(workerState.filepath) === normalizePath(context.__filename)) { + Object.defineProperty(context.__vite_ssr_import_meta__, "vitest", { get: () => globalThis.__vitest_index__ }); + } + return Object.assign(context, { + __vitest_mocker__: this.mocker + }); + } + shouldInterop(path, mod) { + if (this.options.interopDefault === false) + return false; + return (this.options.interopDefault || getCurrentEnvironment() !== "node") && super.shouldInterop(path, mod); + } +} + +export { VitestRunner as V, executeInViteNode as e }; diff --git a/node_modules/vitest/dist/chunk-runtime-rpc.7f83c8a9.js b/node_modules/vitest/dist/chunk-runtime-rpc.7f83c8a9.js new file mode 100644 index 0000000..970ce3e --- /dev/null +++ b/node_modules/vitest/dist/chunk-runtime-rpc.7f83c8a9.js @@ -0,0 +1,30 @@ +import { g as getWorkerState } from './chunk-mock-date.a1c85759.js'; +import { s as safeSetTimeout } from './chunk-utils-timers.52534f96.js'; + +const safeRandom = Math.random; +function withSafeTimers(fn) { + const currentSetTimeout = globalThis.setTimeout; + const currentRandom = globalThis.Math.random; + try { + globalThis.setTimeout = safeSetTimeout; + globalThis.Math.random = safeRandom; + const result = fn(); + return result; + } finally { + globalThis.setTimeout = currentSetTimeout; + globalThis.Math.random = currentRandom; + } +} +const rpc = () => { + const { rpc: rpc2 } = getWorkerState(); + return new Proxy(rpc2, { + get(target, p, handler) { + const sendCall = Reflect.get(target, p, handler); + const safeSendCall = (...args) => withSafeTimers(() => sendCall(...args)); + safeSendCall.asEvent = sendCall.asEvent; + return safeSendCall; + } + }); +}; + +export { rpc as r }; diff --git a/node_modules/vitest/dist/chunk-runtime-setup.731b2b04.js b/node_modules/vitest/dist/chunk-runtime-setup.731b2b04.js new file mode 100644 index 0000000..d8ee714 --- /dev/null +++ b/node_modules/vitest/dist/chunk-runtime-setup.731b2b04.js @@ -0,0 +1,646 @@ +import { performance } from 'perf_hooks'; +import { g as generateHash, c as calculateSuiteHash, s as someTasksAreOnly, i as interpretTaskModes, t as takeCoverageInsideWorker, p as pLimit } from './chunk-integrations-coverage.44413252.js'; +import { f as clearCollectorContext, h as defaultSuite, j as setHooks, k as getHooks, l as collectorContext, m as getBenchOptions, n as getFn, o as setState, p as getSnapshotClient, G as GLOBAL_EXPECT, q as getState } from './chunk-runtime-chain.6df5a66b.js'; +import { r as resetRunOnceCounter, i as index, v as vi, s as setCurrentTest } from './chunk-utils-import.2baa69a9.js'; +import { g as getWorkerState, R as RealDate, t as toArray, k as relativePath, h as isRunningInBenchmark, p as partitionSuiteChildren, l as shuffle, q as hasTests, u as hasFailed, v as createDefer, e as getFullName } from './chunk-mock-date.a1c85759.js'; +import { r as rpc } from './chunk-runtime-rpc.7f83c8a9.js'; +import { p as processError } from './chunk-runtime-error.fad2c32b.js'; +import { installSourcemapsSupport } from 'vite-node/source-map'; +import { e as environments } from './chunk-env-node.b3664da2.js'; +import { i as isNode, a as isBrowser } from './chunk-utils-env.b861e3a0.js'; +import { b as safeClearTimeout, s as safeSetTimeout } from './chunk-utils-timers.52534f96.js'; + +let globalSetup = false; +async function setupGlobalEnv(config) { + resetRunOnceCounter(); + Object.defineProperty(globalThis, "__vitest_index__", { + value: index, + enumerable: false + }); + setupDefines(config.defines); + if (globalSetup) + return; + globalSetup = true; + if (isNode) { + const state = getWorkerState(); + installSourcemapsSupport({ + getSourceMap: (source) => state.moduleCache.getSourceMap(source) + }); + await setupConsoleLogSpy(); + } + if (config.globals) + (await import('./chunk-integrations-globals.3dfaeb99.js')).registerApiGlobally(); +} +function setupDefines(defines) { + for (const key in defines) + globalThis[key] = defines[key]; +} +async function setupConsoleLogSpy() { + const stdoutBuffer = /* @__PURE__ */ new Map(); + const stderrBuffer = /* @__PURE__ */ new Map(); + const timers = /* @__PURE__ */ new Map(); + const unknownTestId = "__vitest__unknown_test__"; + const { Writable } = await import('node:stream'); + const { Console } = await import('node:console'); + function schedule(taskId) { + const timer = timers.get(taskId); + const { stdoutTime, stderrTime } = timer; + safeClearTimeout(timer.timer); + timer.timer = safeSetTimeout(() => { + if (stderrTime < stdoutTime) { + sendStderr(taskId); + sendStdout(taskId); + } else { + sendStdout(taskId); + sendStderr(taskId); + } + }); + } + function sendStdout(taskId) { + const buffer = stdoutBuffer.get(taskId); + if (!buffer) + return; + const content = buffer.map((i) => String(i)).join(""); + if (!content.trim()) + return; + const timer = timers.get(taskId); + rpc().onUserConsoleLog({ + type: "stdout", + content, + taskId, + time: timer.stdoutTime || RealDate.now(), + size: buffer.length + }); + stdoutBuffer.set(taskId, []); + timer.stdoutTime = 0; + } + function sendStderr(taskId) { + const buffer = stderrBuffer.get(taskId); + if (!buffer) + return; + const content = buffer.map((i) => String(i)).join(""); + if (!content.trim()) + return; + const timer = timers.get(taskId); + rpc().onUserConsoleLog({ + type: "stderr", + content, + taskId, + time: timer.stderrTime || RealDate.now(), + size: buffer.length + }); + stderrBuffer.set(taskId, []); + timer.stderrTime = 0; + } + const stdout = new Writable({ + write(data, encoding, callback) { + var _a, _b; + const id = ((_b = (_a = getWorkerState()) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId; + let timer = timers.get(id); + if (timer) { + timer.stdoutTime = timer.stdoutTime || RealDate.now(); + } else { + timer = { stdoutTime: RealDate.now(), stderrTime: RealDate.now(), timer: 0 }; + timers.set(id, timer); + } + let buffer = stdoutBuffer.get(id); + if (!buffer) { + buffer = []; + stdoutBuffer.set(id, buffer); + } + buffer.push(data); + schedule(id); + callback(); + } + }); + const stderr = new Writable({ + write(data, encoding, callback) { + var _a, _b; + const id = ((_b = (_a = getWorkerState()) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId; + let timer = timers.get(id); + if (timer) { + timer.stderrTime = timer.stderrTime || RealDate.now(); + } else { + timer = { stderrTime: RealDate.now(), stdoutTime: RealDate.now(), timer: 0 }; + timers.set(id, timer); + } + let buffer = stderrBuffer.get(id); + if (!buffer) { + buffer = []; + stderrBuffer.set(id, buffer); + } + buffer.push(data); + schedule(id); + callback(); + } + }); + globalThis.console = new Console({ + stdout, + stderr, + colorMode: true, + groupIndentation: 2 + }); +} +async function loadEnvironment(name) { + const pkg = await import(`vitest-environment-${name}`); + if (!pkg || !pkg.default || typeof pkg.default !== "object" || typeof pkg.default.setup !== "function") { + throw new Error( + `Environment "${name}" is not a valid environment. Package "vitest-environment-${name}" should have default export with "setup" method.` + ); + } + return pkg.default; +} +async function withEnv(name, options, fn) { + const config = environments[name] || await loadEnvironment(name); + const env = await config.setup(globalThis, options); + try { + await fn(); + } finally { + await env.teardown(globalThis); + } +} +async function runSetupFiles(config) { + const files = toArray(config.setupFiles); + await Promise.all( + files.map(async (fsPath) => { + getWorkerState().moduleCache.delete(fsPath); + await import(fsPath); + }) + ); +} + +const now$1 = Date.now; +async function collectTests(paths, config) { + const files = []; + const browserHashMap = getWorkerState().browserHashMap; + async function importFromBrowser(filepath) { + const match = filepath.match(/^(\w:\/)/); + const hash = browserHashMap.get(filepath); + if (match) + return await import(`/@fs/${filepath.slice(match[1].length)}?v=${hash}`); + else + return await import(`${filepath}?v=${hash}`); + } + for (const filepath of paths) { + const path = relativePath(config.root, filepath); + const file = { + id: generateHash(path), + name: path, + type: "suite", + mode: "run", + filepath, + tasks: [], + projectName: config.name + }; + clearCollectorContext(); + try { + const setupStart = now$1(); + await runSetupFiles(config); + const collectStart = now$1(); + file.setupDuration = collectStart - setupStart; + if (config.browser && isBrowser) + await importFromBrowser(filepath); + else + await import(filepath); + const defaultTasks = await defaultSuite.collect(file); + setHooks(file, getHooks(defaultTasks)); + for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) { + if (c.type === "test") { + file.tasks.push(c); + } else if (c.type === "benchmark") { + file.tasks.push(c); + } else if (c.type === "suite") { + file.tasks.push(c); + } else if (c.type === "collector") { + const suite = await c.collect(file); + if (suite.name || suite.tasks.length) + file.tasks.push(suite); + } + } + file.collectDuration = now$1() - collectStart; + } catch (e) { + const error = processError(e); + file.result = { + state: "fail", + error, + errors: [error] + }; + if (config.browser) + console.error(e); + } + calculateSuiteHash(file); + const hasOnlyTasks = someTasksAreOnly(file); + interpretTaskModes(file, config.testNamePattern, hasOnlyTasks, false, config.allowOnly); + files.push(file); + } + return files; +} + +async function importTinybench() { + if (!globalThis.EventTarget) + await import('./vendor-index.534e612c.js').then(function (n) { return n.i; }); + return await import('tinybench'); +} +const now = Date.now; +function updateSuiteHookState(suite, name, state) { + var _a; + if (!suite.result) + suite.result = { state: "run" }; + if (!((_a = suite.result) == null ? void 0 : _a.hooks)) + suite.result.hooks = {}; + const suiteHooks = suite.result.hooks; + if (suiteHooks) { + suiteHooks[name] = state; + updateTask(suite); + } +} +function getSuiteHooks(suite, name, sequence) { + const hooks = getHooks(suite)[name]; + if (sequence === "stack" && (name === "afterAll" || name === "afterEach")) + return hooks.slice().reverse(); + return hooks; +} +async function callSuiteHook(suite, currentTask, name, args) { + const callbacks = []; + if (name === "beforeEach" && suite.suite) { + callbacks.push( + ...await callSuiteHook(suite.suite, currentTask, name, args) + ); + } + updateSuiteHookState(currentTask, name, "run"); + const state = getWorkerState(); + const sequence = state.config.sequence.hooks; + const hooks = getSuiteHooks(suite, name, sequence); + if (sequence === "parallel") { + callbacks.push(...await Promise.all(hooks.map((fn) => fn(...args)))); + } else { + for (const hook of hooks) + callbacks.push(await hook(...args)); + } + updateSuiteHookState(currentTask, name, "pass"); + if (name === "afterEach" && suite.suite) { + callbacks.push( + ...await callSuiteHook(suite.suite, currentTask, name, args) + ); + } + return callbacks; +} +const packs = /* @__PURE__ */ new Map(); +let updateTimer; +let previousUpdate; +function updateTask(task) { + packs.set(task.id, task.result); + safeClearTimeout(updateTimer); + updateTimer = safeSetTimeout(() => { + previousUpdate = sendTasksUpdate(); + }, 10); +} +async function sendTasksUpdate() { + safeClearTimeout(updateTimer); + await previousUpdate; + if (packs.size) { + const p = rpc().onTaskUpdate(Array.from(packs)); + packs.clear(); + return p; + } +} +const callCleanupHooks = async (cleanups) => { + await Promise.all(cleanups.map(async (fn) => { + if (typeof fn !== "function") + return; + await fn(); + })); +}; +async function runTest(test) { + var _a, _b, _c; + if (test.mode !== "run") { + const { getSnapshotClient: getSnapshotClient2 } = await import('./chunk-runtime-chain.6df5a66b.js').then(function (n) { return n.u; }); + getSnapshotClient2().skipTestSnapshots(test); + return; + } + if (((_a = test.result) == null ? void 0 : _a.state) === "fail") { + updateTask(test); + return; + } + const start = now(); + test.result = { + state: "run", + startTime: start + }; + updateTask(test); + clearModuleMocks(); + setCurrentTest(test); + if (isNode) { + const { getSnapshotClient: getSnapshotClient2 } = await import('./chunk-runtime-chain.6df5a66b.js').then(function (n) { return n.u; }); + await getSnapshotClient2().setTest(test); + } + const workerState = getWorkerState(); + workerState.current = test; + const retry = test.retry || 1; + for (let retryCount = 0; retryCount < retry; retryCount++) { + let beforeEachCleanups = []; + try { + setState({ + assertionCalls: 0, + isExpectingAssertions: false, + isExpectingAssertionsError: null, + expectedAssertionsNumber: null, + expectedAssertionsNumberErrorGen: null, + testPath: (_b = test.suite.file) == null ? void 0 : _b.filepath, + currentTestName: getFullName(test), + snapshotState: getSnapshotClient().snapshotState + }, globalThis[GLOBAL_EXPECT]); + beforeEachCleanups = await callSuiteHook(test.suite, test, "beforeEach", [test.context, test.suite]); + test.result.retryCount = retryCount; + await getFn(test)(); + const { + assertionCalls, + expectedAssertionsNumber, + expectedAssertionsNumberErrorGen, + isExpectingAssertions, + isExpectingAssertionsError + } = test.context._local ? test.context.expect.getState() : getState(globalThis[GLOBAL_EXPECT]); + if (expectedAssertionsNumber !== null && assertionCalls !== expectedAssertionsNumber) + throw expectedAssertionsNumberErrorGen(); + if (isExpectingAssertions === true && assertionCalls === 0) + throw isExpectingAssertionsError; + test.result.state = "pass"; + } catch (e) { + const error = processError(e); + test.result.state = "fail"; + test.result.error = error; + test.result.errors = [error]; + } + try { + await callSuiteHook(test.suite, test, "afterEach", [test.context, test.suite]); + await callCleanupHooks(beforeEachCleanups); + } catch (e) { + const error = processError(e); + test.result.state = "fail"; + test.result.error = error; + test.result.errors = [error]; + } + if (test.result.state === "pass") + break; + updateTask(test); + } + if (test.result.state === "fail") + await Promise.all(((_c = test.onFailed) == null ? void 0 : _c.map((fn) => fn(test.result))) || []); + if (test.fails) { + if (test.result.state === "pass") { + const error = processError(new Error("Expect test to fail")); + test.result.state = "fail"; + test.result.error = error; + test.result.errors = [error]; + } else { + test.result.state = "pass"; + test.result.error = void 0; + test.result.errors = void 0; + } + } + if (isBrowser && test.result.error) + console.error(test.result.error.message, test.result.error.stackStr); + setCurrentTest(void 0); + if (isNode) { + const { getSnapshotClient: getSnapshotClient2 } = await import('./chunk-runtime-chain.6df5a66b.js').then(function (n) { return n.u; }); + getSnapshotClient2().clearTest(); + } + test.result.duration = now() - start; + if (workerState.config.logHeapUsage && isNode) + test.result.heap = process.memoryUsage().heapUsed; + workerState.current = void 0; + updateTask(test); +} +function markTasksAsSkipped(suite) { + suite.tasks.forEach((t) => { + t.mode = "skip"; + t.result = { ...t.result, state: "skip" }; + updateTask(t); + if (t.type === "suite") + markTasksAsSkipped(t); + }); +} +async function runSuite(suite) { + var _a; + if (((_a = suite.result) == null ? void 0 : _a.state) === "fail") { + markTasksAsSkipped(suite); + updateTask(suite); + return; + } + const start = now(); + suite.result = { + state: "run", + startTime: start + }; + updateTask(suite); + const workerState = getWorkerState(); + if (suite.mode === "skip") { + suite.result.state = "skip"; + } else if (suite.mode === "todo") { + suite.result.state = "todo"; + } else { + try { + const beforeAllCleanups = await callSuiteHook(suite, suite, "beforeAll", [suite]); + if (isRunningInBenchmark()) { + await runBenchmarkSuite(suite); + } else { + for (let tasksGroup of partitionSuiteChildren(suite)) { + if (tasksGroup[0].concurrent === true) { + const mutex = pLimit(workerState.config.maxConcurrency); + await Promise.all(tasksGroup.map((c) => mutex(() => runSuiteChild(c)))); + } else { + const { sequence } = workerState.config; + if (sequence.shuffle || suite.shuffle) { + const suites = tasksGroup.filter((group) => group.type === "suite"); + const tests = tasksGroup.filter((group) => group.type === "test"); + const groups = shuffle([suites, tests], sequence.seed); + tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed)); + } + for (const c of tasksGroup) + await runSuiteChild(c); + } + } + } + await callSuiteHook(suite, suite, "afterAll", [suite]); + await callCleanupHooks(beforeAllCleanups); + } catch (e) { + const error = processError(e); + suite.result.state = "fail"; + suite.result.error = error; + suite.result.errors = [error]; + } + } + suite.result.duration = now() - start; + if (workerState.config.logHeapUsage && isNode) + suite.result.heap = process.memoryUsage().heapUsed; + if (suite.mode === "run") { + if (!hasTests(suite)) { + suite.result.state = "fail"; + if (!suite.result.error) { + const error = processError(new Error(`No test found in suite ${suite.name}`)); + suite.result.error = error; + suite.result.errors = [error]; + } + } else if (hasFailed(suite)) { + suite.result.state = "fail"; + } else { + suite.result.state = "pass"; + } + } + updateTask(suite); +} +function createBenchmarkResult(name) { + return { + name, + rank: 0, + rme: 0, + samples: [] + }; +} +async function runBenchmarkSuite(suite) { + const { Task, Bench } = await importTinybench(); + const start = performance.now(); + const benchmarkGroup = []; + const benchmarkSuiteGroup = []; + for (const task of suite.tasks) { + if (task.mode !== "run") + continue; + if (task.type === "benchmark") + benchmarkGroup.push(task); + else if (task.type === "suite") + benchmarkSuiteGroup.push(task); + } + if (benchmarkSuiteGroup.length) + await Promise.all(benchmarkSuiteGroup.map((subSuite) => runBenchmarkSuite(subSuite))); + if (benchmarkGroup.length) { + const defer = createDefer(); + const benchmarkMap = {}; + suite.result = { + state: "run", + startTime: start, + benchmark: createBenchmarkResult(suite.name) + }; + updateTask(suite); + benchmarkGroup.forEach((benchmark, idx) => { + const options = getBenchOptions(benchmark); + const benchmarkInstance = new Bench(options); + const benchmarkFn = getFn(benchmark); + benchmark.result = { + state: "run", + startTime: start, + benchmark: createBenchmarkResult(benchmark.name) + }; + const id = idx.toString(); + benchmarkMap[id] = benchmark; + const task = new Task(benchmarkInstance, id, benchmarkFn); + benchmark.task = task; + updateTask(benchmark); + }); + benchmarkGroup.forEach((benchmark) => { + benchmark.task.addEventListener("complete", (e) => { + const task = e.task; + const _benchmark = benchmarkMap[task.name || ""]; + if (_benchmark) { + const taskRes = task.result; + const result = _benchmark.result.benchmark; + Object.assign(result, taskRes); + updateTask(_benchmark); + } + }); + benchmark.task.addEventListener("error", (e) => { + const task = e.task; + const _benchmark = benchmarkMap[task.name || ""]; + defer.reject(_benchmark ? task.result.error : e); + }); + }); + Promise.all(benchmarkGroup.map(async (benchmark) => { + await benchmark.task.warmup(); + return await new Promise((resolve) => safeSetTimeout(async () => { + resolve(await benchmark.task.run()); + })); + })).then((tasks) => { + suite.result.duration = performance.now() - start; + suite.result.state = "pass"; + tasks.sort((a, b) => a.result.mean - b.result.mean).forEach((cycle, idx) => { + const benchmark = benchmarkMap[cycle.name || ""]; + benchmark.result.state = "pass"; + if (benchmark) { + const result = benchmark.result.benchmark; + result.rank = Number(idx) + 1; + updateTask(benchmark); + } + }); + updateTask(suite); + defer.resolve(null); + }); + await defer; + } +} +async function runSuiteChild(c) { + if (c.type === "test") + return runTest(c); + else if (c.type === "suite") + return runSuite(c); +} +async function runSuites(suites) { + for (const suite of suites) + await runSuite(suite); +} +async function runFiles(files, config) { + var _a, _b; + for (const file of files) { + if (!file.tasks.length && !config.passWithNoTests) { + if (!((_b = (_a = file.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.length)) { + const error = processError(new Error(`No test suite found in file ${file.filepath}`)); + file.result = { + state: "fail", + error, + errors: [error] + }; + } + } + await runSuite(file); + } +} +async function startTestsBrowser(paths, config) { + if (isNode) { + rpc().onPathsCollected(paths); + } else { + const files = await collectTests(paths, config); + await rpc().onCollected(files); + await runSuites(files); + await sendTasksUpdate(); + } +} +async function startTestsNode(paths, config) { + const files = await collectTests(paths, config); + rpc().onCollected(files); + const { getSnapshotClient: getSnapshotClient2 } = await import('./chunk-runtime-chain.6df5a66b.js').then(function (n) { return n.u; }); + getSnapshotClient2().clear(); + await runFiles(files, config); + const coverage = await takeCoverageInsideWorker(config.coverage); + rpc().onAfterSuiteRun({ coverage }); + await getSnapshotClient2().saveCurrent(); + await sendTasksUpdate(); +} +async function startTests(paths, config) { + if (config.browser) + return startTestsBrowser(paths, config); + else + return startTestsNode(paths, config); +} +function clearModuleMocks() { + const { clearMocks, mockReset, restoreMocks, unstubEnvs, unstubGlobals } = getWorkerState().config; + if (restoreMocks) + vi.restoreAllMocks(); + else if (mockReset) + vi.resetAllMocks(); + else if (clearMocks) + vi.clearAllMocks(); + if (unstubEnvs) + vi.unstubAllEnvs(); + if (unstubGlobals) + vi.unstubAllGlobals(); +} + +export { setupGlobalEnv as a, startTests as s, withEnv as w }; diff --git a/node_modules/vitest/dist/chunk-snapshot-manager.700322bf.js b/node_modules/vitest/dist/chunk-snapshot-manager.700322bf.js new file mode 100644 index 0000000..28f23e3 --- /dev/null +++ b/node_modules/vitest/dist/chunk-snapshot-manager.700322bf.js @@ -0,0 +1,11449 @@ +import { j as join, c as basename, d as dirname, r as relative, e as extname, b as resolve, f as distDir, g as rootDir, h as isAbsolute, i as isNode, k as configFiles, l as defaultPort, n as normalize, t as toNamespacedPath, E as EXIT_CODE_RESTART } from './chunk-utils-env.b861e3a0.js'; +import { p as pLimit, g as generateHash, c as calculateSuiteHash, s as someTasksAreOnly, i as interpretTaskModes, a as getCoverageProvider, C as CoverageProviderMap } from './chunk-integrations-coverage.44413252.js'; +import { g as getEnvPackageName } from './chunk-env-node.b3664da2.js'; +import { y as ensurePackageInstalled, A as AggregateErrorPonyfill, s as slash$1, k as relativePath, z as getTests, e as getFullName, u as hasFailed, B as hasFailedSnapshot, C as getSuites, j as notNullish, l as shuffle, t as toArray, n as noop$1, D as deepMerge, b as getCallLastIndex, E as removeUndefinedValues, F as isWindows, G as stdout } from './chunk-mock-date.a1c85759.js'; +import { loadConfigFromFile, normalizePath, createServer, mergeConfig } from 'vite'; +import path$a from 'node:path'; +import url, { fileURLToPath } from 'node:url'; +import process$1 from 'node:process'; +import fs$8, { promises, existsSync } from 'node:fs'; +import g from 'path'; +import require$$0 from 'os'; +import util$2 from 'util'; +import require$$0$1 from 'stream'; +import require$$2 from 'events'; +import require$$0$2, { existsSync as existsSync$1, readFileSync } from 'fs'; +import { c as commonjsGlobal } from './vendor-_commonjsHelpers.addc3445.js'; +import c from 'picocolors'; +import { ViteNodeRunner } from 'vite-node/client'; +import { ViteNodeServer } from 'vite-node/server'; +import { writeFile, rm } from 'node:fs/promises'; +import { e as execa } from './vendor-index.b2fdde54.js'; +import { SourceMapConsumer } from 'source-map'; +import H from 'module'; +import { parse as parse$4 } from 'acorn'; +import { ancestor } from 'acorn-walk'; +import { MessageChannel } from 'node:worker_threads'; +import { cpus, hostname } from 'node:os'; +import { Tinypool } from 'tinypool'; +import { c as createBirpc } from './vendor-index.783e7f3e.js'; +import { performance } from 'perf_hooks'; +import { s as stripAnsi, c as cliTruncate, b as parseStacktrace, d as stringWidth, e as sliceAnsi, a as positionToOffset, l as lineSplitRE } from './chunk-utils-source-map.60562959.js'; +import { g as safeSetInterval, h as safeClearInterval, s as safeSetTimeout, d as ansiStyles, c as createPatch, a as stringify$5, b as safeClearTimeout } from './chunk-utils-timers.52534f96.js'; +import { resolveModule } from 'local-pkg'; +import { createHash } from 'crypto'; +import { slash as slash$2, cleanUrl } from 'vite-node/utils'; +import { o as onetime } from './vendor-index.9c919048.js'; +import { s as signalExit } from './vendor-index.7a2cebfe.js'; +import { createHash as createHash$1 } from 'node:crypto'; +import MagicString from './chunk-magic-string.3a794426.js'; +import { stripLiteral } from 'strip-literal'; +import require$$0$3 from 'readline'; +import { p as prompts } from './vendor-index.9f20a9be.js'; + +var version$1 = "0.27.0"; + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it. +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both. +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +async function pLocate( + iterable, + tester, + { + concurrency = Number.POSITIVE_INFINITY, + preserveOrder = true, + } = {}, +) { + const limit = pLimit(concurrency); + + // Start all the promises concurrently with optional limit. + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently. + const checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +} + +const typeMappings = { + directory: 'isDirectory', + file: 'isFile', +}; + +function checkType(type) { + if (Object.hasOwnProperty.call(typeMappings, type)) { + return; + } + + throw new Error(`Invalid type specified: ${type}`); +} + +const matchType = (type, stat) => stat[typeMappings[type]](); + +const toPath$1 = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath; + +async function locatePath( + paths, + { + cwd = process$1.cwd(), + type = 'file', + allowSymlinks = true, + concurrency, + preserveOrder, + } = {}, +) { + checkType(type); + cwd = toPath$1(cwd); + + const statFunction = allowSymlinks ? promises.stat : promises.lstat; + + return pLocate(paths, async path_ => { + try { + const stat = await statFunction(path$a.resolve(cwd, path_)); + return matchType(type, stat); + } catch { + return false; + } + }, {concurrency, preserveOrder}); +} + +const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath; + +const findUpStop = Symbol('findUpStop'); + +async function findUpMultiple(name, options = {}) { + let directory = path$a.resolve(toPath(options.cwd) || ''); + const {root} = path$a.parse(directory); + const stopAt = path$a.resolve(directory, options.stopAt || root); + const limit = options.limit || Number.POSITIVE_INFINITY; + const paths = [name].flat(); + + const runMatcher = async locateOptions => { + if (typeof name !== 'function') { + return locatePath(paths, locateOptions); + } + + const foundPath = await name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath([foundPath], locateOptions); + } + + return foundPath; + }; + + const matches = []; + // eslint-disable-next-line no-constant-condition + while (true) { + // eslint-disable-next-line no-await-in-loop + const foundPath = await runMatcher({...options, cwd: directory}); + + if (foundPath === findUpStop) { + break; + } + + if (foundPath) { + matches.push(path$a.resolve(directory, foundPath)); + } + + if (directory === stopAt || matches.length >= limit) { + break; + } + + directory = path$a.dirname(directory); + } + + return matches; +} + +async function findUp(name, options = {}) { + const matches = await findUpMultiple(name, {...options, limit: 1}); + return matches[0]; +} + +var tasks = {}; + +var utils$k = {}; + +var array$1 = {}; + +Object.defineProperty(array$1, "__esModule", { value: true }); +array$1.splitWhen = array$1.flatten = void 0; +function flatten(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); +} +array$1.flatten = flatten; +function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } + else { + result[groupIndex].push(item); + } + } + return result; +} +array$1.splitWhen = splitWhen; + +var errno$1 = {}; + +Object.defineProperty(errno$1, "__esModule", { value: true }); +errno$1.isEnoentCodeError = void 0; +function isEnoentCodeError(error) { + return error.code === 'ENOENT'; +} +errno$1.isEnoentCodeError = isEnoentCodeError; + +var fs$7 = {}; + +Object.defineProperty(fs$7, "__esModule", { value: true }); +fs$7.createDirentFromStats = void 0; +class DirentFromStats$1 { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats$1(name, stats) { + return new DirentFromStats$1(name, stats); +} +fs$7.createDirentFromStats = createDirentFromStats$1; + +var path$9 = {}; + +Object.defineProperty(path$9, "__esModule", { value: true }); +path$9.removeLeadingDotSegment = path$9.escape = path$9.makeAbsolute = path$9.unixify = void 0; +const path$8 = g; +const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ +const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; +/** + * Designed to work only with simple paths: `dir\\file`. + */ +function unixify(filepath) { + return filepath.replace(/\\/g, '/'); +} +path$9.unixify = unixify; +function makeAbsolute(cwd, filepath) { + return path$8.resolve(cwd, filepath); +} +path$9.makeAbsolute = makeAbsolute; +function escape(pattern) { + return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +path$9.escape = escape; +function removeLeadingDotSegment(entry) { + // We do not use `startsWith` because this is 10x slower than current implementation for some cases. + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (entry.charAt(0) === '.') { + const secondCharactery = entry.charAt(1); + if (secondCharactery === '/' || secondCharactery === '\\') { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + } + return entry; +} +path$9.removeLeadingDotSegment = removeLeadingDotSegment; + +var pattern$1 = {}; + +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +var isExtglob$1 = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; + +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var isExtglob = isExtglob$1; +var chars = { '{': '}', '(': ')', '[': ']'}; +var strictCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + var pipeIndex = -2; + var closeSquareIndex = -2; + var closeCurlyIndex = -2; + var closeParenIndex = -2; + var backSlashIndex = -2; + while (index < str.length) { + if (str[index] === '*') { + return true; + } + + if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { + return true; + } + + if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { + if (closeSquareIndex < index) { + closeSquareIndex = str.indexOf(']', index); + } + if (closeSquareIndex > index) { + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + } + } + + if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { + closeCurlyIndex = str.indexOf('}', index); + if (closeCurlyIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { + return true; + } + } + } + + if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { + closeParenIndex = str.indexOf(')', index); + if (closeParenIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + + if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { + if (pipeIndex < index) { + pipeIndex = str.indexOf('|', index); + } + if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { + closeParenIndex = str.indexOf(')', pipeIndex); + if (closeParenIndex > pipeIndex) { + backSlashIndex = str.indexOf('\\', pipeIndex); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +var relaxedCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + while (index < str.length) { + if (/[*?{}()[\]]/.test(str[index])) { + return true; + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +var isGlob$1 = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var check = strictCheck; + + // optionally relax check + if (options && options.strict === false) { + check = relaxedCheck; + } + + return check(str); +}; + +var isGlob = isGlob$1; +var pathPosixDirname = g.posix.dirname; +var isWin32 = require$$0.platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\}\]]$/; +var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + * @returns {string} + */ +var globParent$1 = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (enclosure.test(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; + +var utils$j = {}; + +(function (exports) { + + exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; + }; + + /** + * Find a node of the given type + */ + + exports.find = (node, type) => node.nodes.find(node => node.type === type); + + /** + * Find a node of the given type + */ + + exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; + }; + + /** + * Escape the given node with '\\' before node.value + */ + + exports.escapeNode = (block, n = 0, type) => { + let node = block.nodes[n]; + if (!node) return; + + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } + }; + + /** + * Returns true if the given brace node should be enclosed in literal braces + */ + + exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; + }; + + /** + * Returns true if a brace node is invalid. + */ + + exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; + }; + + /** + * Returns true if a node is an open or close node + */ + + exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; + }; + + /** + * Reduce an array of text nodes. + */ + + exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; + }, []); + + /** + * Flatten an array + */ + + exports.flatten = (...args) => { + const result = []; + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); + } + return result; + }; + flat(args); + return result; + }; +} (utils$j)); + +const utils$i = utils$j; + +var stringify$4 = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils$i.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils$i.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +var isNumber$2 = function(num) { + if (typeof num === 'number') { + return num - num === 0; + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + return false; +}; + +/*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + +const isNumber$1 = isNumber$2; + +const toRegexRange$1 = (min, max, options) => { + if (isNumber$1(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber$1(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) { + return toRegexRange$1.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange$1.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false) || []; + let onlyPositive = filterPatterns(pos, neg, '', false) || []; + let intersected = filterPatterns(neg, pos, '-?', true) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); + + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { pattern, count: [count], digits }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { string } = ele; + + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } + + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} + +/** + * Zip strings + */ + +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} + +/** + * Cache + */ + +toRegexRange$1.cache = {}; +toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {}); + +/** + * Expose `toRegexRange` + */ + +var toRegexRange_1 = toRegexRange$1; + +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ + +const util$1 = util$2; +const toRegexRange = toRegexRange_1; + +const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val); + +const transform$1 = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; + +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; + +const isNumber = num => Number.isInteger(+num); + +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; + +const stringify$3 = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; + +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; + +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; + +const toSequence = (parts, options) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; + + if (parts.positives.length) { + positives = parts.positives.join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.join('|')})`; + } + + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + + if (options.wrap) { + return `(${prefix}${result})`; + } + + return result; +}; + +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, { wrap: false, ...options }); + } + + let start = String.fromCharCode(a); + if (a === b) return start; + + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; + +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange(start, end, options); +}; + +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util$1.inspect(...args)); +}; + +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; + +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; + +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } + + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; + + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify$3(start, end, options) === false; + let format = options.transform || transform$1(toNumber); + + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options) + : toRegex(range, null, { wrap: false, ...options }); + } + + return range; +}; + +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { + return invalidRange(start, end, options); + } + + + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } + + return range; +}; + +const fill$2 = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + + if (typeof step === 'function') { + return fill$2(start, end, 1, { transform: step }); + } + + if (isObject$1(step)) { + return fill$2(start, end, 0, step); + } + + let opts = { ...options }; + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + + if (!isNumber(step)) { + if (step != null && !isObject$1(step)) return invalidStep(step, opts); + return fill$2(start, end, 1, step); + } + + if (isNumber(start) && isNumber(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +var fillRange = fill$2; + +const fill$1 = fillRange; +const utils$h = utils$j; + +const compile$1 = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils$h.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + if (node.isClose === true) { + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? (prefix + node.value) : '('; + } + + if (node.type === 'close') { + return invalid ? (prefix + node.value) : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$h.reduce(node.nodes); + let range = fill$1(...args, { ...options, wrap: false, toRegex: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + return output; + }; + + return walk(ast); +}; + +var compile_1 = compile$1; + +const fill = fillRange; +const stringify$2 = stringify$4; +const utils$g = utils$j; + +const append = (queue = '', stash = '', enclose = false) => { + let result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils$g.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); + } + } + } + return utils$g.flatten(result); +}; + +const expand$1 = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + + let walk = (node, parent = {}) => { + node.queue = []; + + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify$2(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$g.reduce(node.nodes); + + if (utils$g.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fill(...args, options); + if (range.length === 0) { + range = stringify$2(node, options); + } + + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + + let enclose = utils$g.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils$g.flatten(walk(ast)); +}; + +var expand_1 = expand$1; + +var constants$4 = { + MAX_LENGTH: 1024 * 64, + + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ + + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + + CHAR_ASTERISK: '*', /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; + +const stringify$1 = stringify$4; + +/** + * Constants + */ + +const { + MAX_LENGTH: MAX_LENGTH$1, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA: CHAR_COMMA$1, /* , */ + CHAR_DOT: CHAR_DOT$1, /* . */ + CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ + CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ + CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ + CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ + CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */ + CHAR_DOUBLE_QUOTE, /* " */ + CHAR_SINGLE_QUOTE, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = constants$4; + +/** + * parse + */ + +const parse$3 = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + let opts = options || {}; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + let ast = { type: 'root', input, nodes: [] }; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let length = input.length; + let index = 0; + let depth = 0; + let value; + + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ type: 'bos' }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + + /** + * Escaped chars + */ + + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } + + /** + * Right square bracket (literal): ']' + */ + + if (value === CHAR_RIGHT_SQUARE_BRACKET$1) { + push({ type: 'text', value: '\\' + value }); + continue; + } + + /** + * Left square bracket: '[' + */ + + if (value === CHAR_LEFT_SQUARE_BRACKET$1) { + brackets++; + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET$1) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES$1) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES$1) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; + } + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } + + /** + * Quotes: '|"|` + */ + + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + let open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Left curly brace: '{' + */ + + if (value === CHAR_LEFT_CURLY_BRACE$1) { + depth++; + + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } + + /** + * Right curly brace: '}' + */ + + if (value === CHAR_RIGHT_CURLY_BRACE$1) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + + let type = 'close'; + block = stack.pop(); + block.close = true; + + push({ type, value }); + depth--; + + block = stack[stack.length - 1]; + continue; + } + + /** + * Comma: ',' + */ + + if (value === CHAR_COMMA$1 && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + let open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify$1(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) { + let siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + + let before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); + } + + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); + + // get the location of the block on parent.nodes (block's siblings) + let parent = stack[stack.length - 1]; + let index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +var parse_1$1 = parse$3; + +const stringify = stringify$4; +const compile = compile_1; +const expand = expand_1; +const parse$2 = parse_1$1; + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces$1 = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces$1.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces$1.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + +braces$1.parse = (input, options = {}) => parse$2(input, options); + +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$1.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify(braces$1.parse(input, options), options); + } + return stringify(input, options); +}; + +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$1.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces$1.parse(input, options); + } + return compile(input, options); +}; + +/** + * 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 [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$1.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces$1.parse(input, options); + } + + let result = expand(input, options); + + // filter out empty strings if specified + if (options.noempty === true) { + result = result.filter(Boolean); + } + + // filter out duplicates if specified + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; + +/** + * 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. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$1.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true + ? braces$1.compile(input, options) + : braces$1.expand(input, options); +}; + +/** + * Expose "braces" + */ + +var braces_1 = braces$1; + +var picomatch$2 = {exports: {}}; + +var utils$f = {}; + +const path$7 = g; +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; + +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; + +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = { + ...POSIX_CHARS, + + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; + +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE$1 = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + +var constants$3 = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, + + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ + + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ + + CHAR_ASTERISK: 42, /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + + SEP: path$7.sep, + + /** + * Create EXTGLOB_CHARS + */ + + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, + + /** + * Create GLOB_CHARS + */ + + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; + +(function (exports) { + + const path = g; + const win32 = process.platform === 'win32'; + const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL + } = constants$3; + + exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); + exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); + exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); + exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); + exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + + exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); + }; + + exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; + }; + + exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path.sep === '\\'; + }; + + exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; + }; + + exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; + }; + + exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; + }; +} (utils$f)); + +const utils$e = utils$f; +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET /* ] */ +} = constants$3; + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; + +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + +const scan$1 = (input, options) => { + const opts = options || {}; + + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; + + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; + + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; + } + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; + } + break; + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils$e.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils$e.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +var scan_1 = scan$1; + +const constants$2 = constants$3; +const utils$d = utils$f; + +/** + * Constants + */ + +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants$2; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils$d.escapeRegex(v)).join('..'); + } + + return value; +}; + +/** + * Create the message for a syntax error + */ + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; + +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse$1 = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; + + const capture = opts.capture ? '' : '?:'; + const win32 = utils$d.isWindows(options); + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants$2.globChars(win32); + const EXTGLOB_CHARS = constants$2.extglobChars(PLATFORM_CHARS); + + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + + input = utils$d.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + let rest; + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. + // In this case, we need to parse the string and use it in the output of the original pattern. + // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. + // + // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. + const expression = parse$1(rest, { ...options, fastpaths: false }).output; + + output = token.close = `)${expression})${extglobStar})`; + } + + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils$d.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils$d.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Square brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + decrement('brackets'); + + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils$d.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils$d.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } + + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } + + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ type: 'comma', value, output }); + continue; + } + + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } + + /** + * Dots + */ + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } + + /** + * Question marks + */ + + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if (next === '<' && !utils$d.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } + + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } + + push({ type: 'text', value, output }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } + + push({ type: 'qmark', value, output: QMARK }); + continue; + } + + /** + * Exclamation + */ + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Plain text + */ + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Stars + */ + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + + state.output += prior.output + prev.output; + state.globstar = true; + + consume(value + advance()); + + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils$d.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils$d.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils$d.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse$1.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + const win32 = utils$d.isWindows(options); + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants$2.globChars(win32); + + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils$d.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +var parse_1 = parse$1; + +const path$6 = g; +const scan = scan_1; +const parse = parse_1; +const utils$c = utils$f; +const constants$1 = constants$3; +const isObject = val => val && typeof val === 'object' && !Array.isArray(val); + +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + +const picomatch$1 = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch$1(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + + const isState = isObject(glob) && glob.tokens && glob.input; + + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = utils$c.isWindows(options); + const regex = isState + ? picomatch$1.compileRe(glob, options) + : picomatch$1.makeRe(glob, options, false, true); + + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; + +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + +picomatch$1.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils$c.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch$1.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { isMatch: Boolean(match), match, output }; +}; + +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch$1.matchBase = (input, glob, options, posix = utils$c.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options); + return regex.test(path$6.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + +picomatch$1.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options)); + return parse(pattern, { ...options, fastpaths: false }); +}; + +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +picomatch$1.scan = (input, options) => scan(input, options); + +/** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ + +picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch$1.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } + + return regex; +}; + +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + let parsed = { negated: false, fastpaths: true }; + + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse(input, options); + } + + return picomatch$1.compileRe(parsed, options, returnOutput, returnState); +}; + +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +picomatch$1.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; + +/** + * Picomatch constants. + * @return {Object} + */ + +picomatch$1.constants = constants$1; + +/** + * Expose "picomatch" + */ + +var picomatch_1 = picomatch$1; + +(function (module) { + + module.exports = picomatch_1; +} (picomatch$2)); + +const util = util$2; +const braces = braces_1; +const picomatch = picomatch$2.exports; +const utils$b = utils$f; +const isEmptyString = val => val === '' || val === './'; + +/** + * Returns an array of strings that match one or more glob patterns. + * + * ```js + * const mm = require('micromatch'); + * // mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {String|Array} `list` List of strings to match. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + +const micromatch$1 = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); + + let omit = new Set(); + let keep = new Set(); + let items = new Set(); + let negatives = 0; + + let onResult = state => { + items.add(state.output); + if (options && options.onResult) { + options.onResult(state); + } + }; + + for (let i = 0; i < patterns.length; i++) { + let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) negatives++; + + for (let item of list) { + let matched = isMatch(item, true); + + let match = negated ? !matched.isMatch : matched.isMatch; + if (!match) continue; + + if (negated) { + omit.add(matched.output); + } else { + omit.delete(matched.output); + keep.add(matched.output); + } + } + } + + let result = negatives === patterns.length ? [...items] : [...keep]; + let matches = result.filter(item => !omit.has(item)); + + if (options && matches.length === 0) { + if (options.failglob === true) { + throw new Error(`No matches found for "${patterns.join(', ')}"`); + } + + if (options.nonull === true || options.nullglob === true) { + return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; + } + } + + return matches; +}; + +/** + * Backwards compatibility + */ + +micromatch$1.match = micromatch$1; + +/** + * Returns a matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * const mm = require('micromatch'); + * // mm.matcher(pattern[, options]); + * + * const isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` + * @return {Function} Returns a matcher function. + * @api public + */ + +micromatch$1.matcher = (pattern, options) => picomatch(pattern, options); + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const mm = require('micromatch'); + * // mm.isMatch(string, patterns[, options]); + * + * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(mm.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `[options]` See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch$1.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + +/** + * Backwards compatibility + */ + +micromatch$1.any = micromatch$1.isMatch; + +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +micromatch$1.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = new Set(); + let items = []; + + let onResult = state => { + if (options.onResult) options.onResult(state); + items.push(state.output); + }; + + let matches = new Set(micromatch$1(list, patterns, { ...options, onResult })); + + for (let item of items) { + if (!matches.has(item)) { + result.add(item); + } + } + return [...result]; +}; + +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * // mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any of the patterns matches any part of `str`. + * @api public + */ + +micromatch$1.contains = (str, pattern, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } + + if (Array.isArray(pattern)) { + return pattern.some(p => micromatch$1.contains(str, p, options)); + } + + if (typeof pattern === 'string') { + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } + + if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { + return true; + } + } + + return micromatch$1.isMatch(str, pattern, { ...options, contains: true }); +}; + +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * const mm = require('micromatch'); + * // mm.matchKeys(object, patterns[, options]); + * + * const obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + +micromatch$1.matchKeys = (obj, patterns, options) => { + if (!utils$b.isObject(obj)) { + throw new TypeError('Expected the first argument to be an object'); + } + let keys = micromatch$1(Object.keys(obj), patterns, options); + let res = {}; + for (let key of keys) res[key] = obj[key]; + return res; +}; + +/** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` + * @api public + */ + +micromatch$1.some = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (items.some(item => isMatch(item))) { + return true; + } + } + return false; +}; + +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` + * @api public + */ + +micromatch$1.every = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (!items.every(item => isMatch(item))) { + return false; + } + } + return true; +}; + +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * const mm = require('micromatch'); + * // mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch$1.all = (str, patterns, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } + + return [].concat(patterns).every(p => picomatch(p, options)(str)); +}; + +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * const mm = require('micromatch'); + * // mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `glob` Glob pattern to use for matching. + * @param {String} `input` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. + * @api public + */ + +micromatch$1.capture = (glob, input, options) => { + let posix = utils$b.isWindows(options); + let regex = picomatch.makeRe(String(glob), { ...options, capture: true }); + let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input); + + if (match) { + return match.slice(1).map(v => v === void 0 ? '' : v); + } +}; + +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * const mm = require('micromatch'); + * // mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +micromatch$1.makeRe = (...args) => picomatch.makeRe(...args); + +/** + * Scan a glob pattern to separate the pattern into segments. Used + * by the [split](#split) method. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.scan(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +micromatch$1.scan = (...args) => picomatch.scan(...args); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.parse(pattern[, options]); + * ``` + * @param {String} `glob` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as regex source string. + * @api public + */ + +micromatch$1.parse = (patterns, options) => { + let res = []; + for (let pattern of [].concat(patterns || [])) { + for (let str of braces(String(pattern), options)) { + res.push(picomatch.parse(str, options)); + } + } + return res; +}; + +/** + * Process the given brace `pattern`. + * + * ```js + * const { braces } = require('micromatch'); + * console.log(braces('foo/{a,b,c}/bar')); + * //=> [ 'foo/(a|b|c)/bar' ] + * + * console.log(braces('foo/{a,b,c}/bar', { expand: true })); + * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] + * ``` + * @param {String} `pattern` String with brace pattern to process. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ + +micromatch$1.braces = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { + return [pattern]; + } + return braces(pattern, options); +}; + +/** + * Expand braces + */ + +micromatch$1.braceExpand = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + return micromatch$1.braces(pattern, { ...options, expand: true }); +}; + +/** + * Expose micromatch + */ + +var micromatch_1 = micromatch$1; + +Object.defineProperty(pattern$1, "__esModule", { value: true }); +pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0; +const path$5 = g; +const globParent = globParent$1; +const micromatch = micromatch_1; +const GLOBSTAR = '**'; +const ESCAPE_SYMBOL = '\\'; +const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; +const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; +const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; +const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; +const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; +function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); +} +pattern$1.isStaticPattern = isStaticPattern; +function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === '') { + return false; + } + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { + return true; + } + return false; +} +pattern$1.isDynamicPattern = isDynamicPattern; +function hasBraceExpansion(pattern) { + const openingBraceIndex = pattern.indexOf('{'); + if (openingBraceIndex === -1) { + return false; + } + const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); + if (closingBraceIndex === -1) { + return false; + } + const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); + return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); +} +function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; +} +pattern$1.convertToPositivePattern = convertToPositivePattern; +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +pattern$1.convertToNegativePattern = convertToNegativePattern; +function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; +} +pattern$1.isNegativePattern = isNegativePattern; +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +pattern$1.isPositivePattern = isPositivePattern; +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +pattern$1.getNegativePatterns = getNegativePatterns; +function getPositivePatterns$1(patterns) { + return patterns.filter(isPositivePattern); +} +pattern$1.getPositivePatterns = getPositivePatterns$1; +/** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsInsideCurrentDirectory(patterns) { + return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); +} +pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; +/** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsOutsideCurrentDirectory(patterns) { + return patterns.filter(isPatternRelatedToParentDirectory); +} +pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; +function isPatternRelatedToParentDirectory(pattern) { + return pattern.startsWith('..') || pattern.startsWith('./..'); +} +pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; +function getBaseDirectory(pattern) { + return globParent(pattern, { flipBackslashes: false }); +} +pattern$1.getBaseDirectory = getBaseDirectory; +function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR); +} +pattern$1.hasGlobStar = hasGlobStar; +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR); +} +pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar; +function isAffectDepthOfReadingPattern(pattern) { + const basename = path$5.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); +} +pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; +function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); +} +pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; +function expandBraceExpansion(pattern) { + return micromatch.braces(pattern, { + expand: true, + nodupes: true + }); +} +pattern$1.expandBraceExpansion = expandBraceExpansion; +function getPatternParts(pattern, options) { + let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + if (parts.length === 0) { + parts = [pattern]; + } + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + if (parts[0].startsWith('/')) { + parts[0] = parts[0].slice(1); + parts.unshift(''); + } + return parts; +} +pattern$1.getPatternParts = getPatternParts; +function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); +} +pattern$1.makeRe = makeRe; +function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe(pattern, options)); +} +pattern$1.convertPatternsToRe = convertPatternsToRe; +function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); +} +pattern$1.matchAny = matchAny; + +var stream$4 = {}; + +/* + * merge2 + * https://github.com/teambition/merge2 + * + * Copyright (c) 2014-2020 Teambition + * Licensed under the MIT license. + */ +const Stream = require$$0$1; +const PassThrough = Stream.PassThrough; +const slice = Array.prototype.slice; + +var merge2_1 = merge2$1; + +function merge2$1 () { + const streamsQueue = []; + const args = slice.call(arguments); + let merging = false; + let options = args[args.length - 1]; + + if (options && !Array.isArray(options) && options.pipe == null) { + args.pop(); + } else { + options = {}; + } + + const doEnd = options.end !== false; + const doPipeError = options.pipeError === true; + if (options.objectMode == null) { + options.objectMode = true; + } + if (options.highWaterMark == null) { + options.highWaterMark = 64 * 1024; + } + const mergedStream = PassThrough(options); + + function addStream () { + for (let i = 0, len = arguments.length; i < len; i++) { + streamsQueue.push(pauseStreams(arguments[i], options)); + } + mergeStream(); + return this + } + + function mergeStream () { + if (merging) { + return + } + merging = true; + + let streams = streamsQueue.shift(); + if (!streams) { + process.nextTick(endStream); + return + } + if (!Array.isArray(streams)) { + streams = [streams]; + } + + let pipesCount = streams.length + 1; + + function next () { + if (--pipesCount > 0) { + return + } + merging = false; + mergeStream(); + } + + function pipe (stream) { + function onend () { + stream.removeListener('merge2UnpipeEnd', onend); + stream.removeListener('end', onend); + if (doPipeError) { + stream.removeListener('error', onerror); + } + next(); + } + function onerror (err) { + mergedStream.emit('error', err); + } + // skip ended stream + if (stream._readableState.endEmitted) { + return next() + } + + stream.on('merge2UnpipeEnd', onend); + stream.on('end', onend); + + if (doPipeError) { + stream.on('error', onerror); + } + + stream.pipe(mergedStream, { end: false }); + // compatible for old stream + stream.resume(); + } + + for (let i = 0; i < streams.length; i++) { + pipe(streams[i]); + } + + next(); + } + + function endStream () { + merging = false; + // emit 'queueDrain' when all streams merged. + mergedStream.emit('queueDrain'); + if (doEnd) { + mergedStream.end(); + } + } + + mergedStream.setMaxListeners(0); + mergedStream.add = addStream; + mergedStream.on('unpipe', function (stream) { + stream.emit('merge2UnpipeEnd'); + }); + + if (args.length) { + addStream.apply(null, args); + } + return mergedStream +} + +// check and pause streams for pipe. +function pauseStreams (streams, options) { + if (!Array.isArray(streams)) { + // Backwards-compat with old-style streams + if (!streams._readableState && streams.pipe) { + streams = streams.pipe(PassThrough(options)); + } + if (!streams._readableState || !streams.pause || !streams.pipe) { + throw new Error('Only readable stream can be merged.') + } + streams.pause(); + } else { + for (let i = 0, len = streams.length; i < len; i++) { + streams[i] = pauseStreams(streams[i], options); + } + } + return streams +} + +Object.defineProperty(stream$4, "__esModule", { value: true }); +stream$4.merge = void 0; +const merge2 = merge2_1; +function merge(streams) { + const mergedStream = merge2(streams); + streams.forEach((stream) => { + stream.once('error', (error) => mergedStream.emit('error', error)); + }); + mergedStream.once('close', () => propagateCloseEventToSources(streams)); + mergedStream.once('end', () => propagateCloseEventToSources(streams)); + return mergedStream; +} +stream$4.merge = merge; +function propagateCloseEventToSources(streams) { + streams.forEach((stream) => stream.emit('close')); +} + +var string$1 = {}; + +Object.defineProperty(string$1, "__esModule", { value: true }); +string$1.isEmpty = string$1.isString = void 0; +function isString(input) { + return typeof input === 'string'; +} +string$1.isString = isString; +function isEmpty(input) { + return input === ''; +} +string$1.isEmpty = isEmpty; + +Object.defineProperty(utils$k, "__esModule", { value: true }); +utils$k.string = utils$k.stream = utils$k.pattern = utils$k.path = utils$k.fs = utils$k.errno = utils$k.array = void 0; +const array = array$1; +utils$k.array = array; +const errno = errno$1; +utils$k.errno = errno; +const fs$6 = fs$7; +utils$k.fs = fs$6; +const path$4 = path$9; +utils$k.path = path$4; +const pattern = pattern$1; +utils$k.pattern = pattern; +const stream$3 = stream$4; +utils$k.stream = stream$3; +const string = string$1; +utils$k.string = string; + +Object.defineProperty(tasks, "__esModule", { value: true }); +tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0; +const utils$a = utils$k; +function generate(patterns, settings) { + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); + const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); + return staticTasks.concat(dynamicTasks); +} +tasks.generate = generate; +/** + * Returns tasks grouped by basic pattern directories. + * + * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. + * This is necessary because directory traversal starts at the base directory and goes deeper. + */ +function convertPatternsToTasks(positive, negative, dynamic) { + const tasks = []; + const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive); + const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive); + const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); + const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); + tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); + /* + * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory + * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. + */ + if ('.' in insideCurrentDirectoryGroup) { + tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); + } + else { + tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + } + return tasks; +} +tasks.convertPatternsToTasks = convertPatternsToTasks; +function getPositivePatterns(patterns) { + return utils$a.pattern.getPositivePatterns(patterns); +} +tasks.getPositivePatterns = getPositivePatterns; +function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils$a.pattern.convertToPositivePattern); + return positive; +} +tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive; +function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils$a.pattern.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } + else { + collection[base] = [pattern]; + } + return collection; + }, group); +} +tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; +function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); +} +tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks; +function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern)) + }; +} +tasks.convertPatternGroupToTask = convertPatternGroupToTask; + +var patterns = {}; + +Object.defineProperty(patterns, "__esModule", { value: true }); +patterns.removeDuplicateSlashes = patterns.transform = void 0; +/** + * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. + * The latter is due to the presence of the device path at the beginning of the UNC path. + * @todo rewrite to negative lookbehind with the next major release. + */ +const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; +function transform(patterns) { + return patterns.map((pattern) => removeDuplicateSlashes(pattern)); +} +patterns.transform = transform; +/** + * This package only works with forward slashes as a path separator. + * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. + */ +function removeDuplicateSlashes(pattern) { + return pattern.replace(DOUBLE_SLASH_RE, '/'); +} +patterns.removeDuplicateSlashes = removeDuplicateSlashes; + +var async$7 = {}; + +var async$6 = {}; + +var out$3 = {}; + +var async$5 = {}; + +var async$4 = {}; + +var out$2 = {}; + +var async$3 = {}; + +var out$1 = {}; + +var async$2 = {}; + +Object.defineProperty(async$2, "__esModule", { value: true }); +async$2.read = void 0; +function read$3(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + callFailureCallback$2(callback, lstatError); + return; + } + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + callSuccessCallback$2(callback, lstat); + return; + } + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + callFailureCallback$2(callback, statError); + return; + } + callSuccessCallback$2(callback, lstat); + return; + } + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + callSuccessCallback$2(callback, stat); + }); + }); +} +async$2.read = read$3; +function callFailureCallback$2(callback, error) { + callback(error); +} +function callSuccessCallback$2(callback, result) { + callback(null, result); +} + +var sync$7 = {}; + +Object.defineProperty(sync$7, "__esModule", { value: true }); +sync$7.read = void 0; +function read$2(path, settings) { + const lstat = settings.fs.lstatSync(path); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + try { + const stat = settings.fs.statSync(path); + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + return stat; + } + catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + throw error; + } +} +sync$7.read = read$2; + +var settings$3 = {}; + +var fs$5 = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; + const fs = require$$0$2; + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync + }; + function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); + } + exports.createFileSystemAdapter = createFileSystemAdapter; +} (fs$5)); + +Object.defineProperty(settings$3, "__esModule", { value: true }); +const fs$4 = fs$5; +class Settings$2 { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs$4.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +settings$3.default = Settings$2; + +Object.defineProperty(out$1, "__esModule", { value: true }); +out$1.statSync = out$1.stat = out$1.Settings = void 0; +const async$1 = async$2; +const sync$6 = sync$7; +const settings_1$3 = settings$3; +out$1.Settings = settings_1$3.default; +function stat(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async$1.read(path, getSettings$2(), optionsOrSettingsOrCallback); + return; + } + async$1.read(path, getSettings$2(optionsOrSettingsOrCallback), callback); +} +out$1.stat = stat; +function statSync(path, optionsOrSettings) { + const settings = getSettings$2(optionsOrSettings); + return sync$6.read(path, settings); +} +out$1.statSync = statSync; +function getSettings$2(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$3.default) { + return settingsOrOptions; + } + return new settings_1$3.default(settingsOrOptions); +} + +/*! queue-microtask. MIT License. Feross Aboukhadijeh */ + +let promise; + +var queueMicrotask_1 = typeof queueMicrotask === 'function' + ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal) + // reuse resolved promise, and allocate it lazily + : cb => (promise || (promise = Promise.resolve())) + .then(cb) + .catch(err => setTimeout(() => { throw err }, 0)); + +/*! run-parallel. MIT License. Feross Aboukhadijeh */ + +var runParallel_1 = runParallel; + +const queueMicrotask$1 = queueMicrotask_1; + +function runParallel (tasks, cb) { + let results, pending, keys; + let isSync = true; + + if (Array.isArray(tasks)) { + results = []; + pending = tasks.length; + } else { + keys = Object.keys(tasks); + results = {}; + pending = keys.length; + } + + function done (err) { + function end () { + if (cb) cb(err, results); + cb = null; + } + if (isSync) queueMicrotask$1(end); + else end(); + } + + function each (i, err, result) { + results[i] = result; + if (--pending === 0 || err) { + done(err); + } + } + + if (!pending) { + // empty + done(null); + } else if (keys) { + // object + keys.forEach(function (key) { + tasks[key](function (err, result) { each(key, err, result); }); + }); + } else { + // array + tasks.forEach(function (task, i) { + task(function (err, result) { each(i, err, result); }); + }); + } + + isSync = false; +} + +var constants = {}; + +Object.defineProperty(constants, "__esModule", { value: true }); +constants.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; +const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); +if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { + throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); +} +const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); +const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); +const SUPPORTED_MAJOR_VERSION = 10; +const SUPPORTED_MINOR_VERSION = 10; +const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; +const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; +/** + * IS `true` for Node.js 10.10 and greater. + */ +constants.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; + +var utils$9 = {}; + +var fs$3 = {}; + +Object.defineProperty(fs$3, "__esModule", { value: true }); +fs$3.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +fs$3.createDirentFromStats = createDirentFromStats; + +Object.defineProperty(utils$9, "__esModule", { value: true }); +utils$9.fs = void 0; +const fs$2 = fs$3; +utils$9.fs = fs$2; + +var common$6 = {}; + +Object.defineProperty(common$6, "__esModule", { value: true }); +common$6.joinPathSegments = void 0; +function joinPathSegments$1(a, b, separator) { + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +common$6.joinPathSegments = joinPathSegments$1; + +Object.defineProperty(async$3, "__esModule", { value: true }); +async$3.readdir = async$3.readdirWithFileTypes = async$3.read = void 0; +const fsStat$5 = out$1; +const rpl = runParallel_1; +const constants_1$1 = constants; +const utils$8 = utils$9; +const common$5 = common$6; +function read$1(directory, settings, callback) { + if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + readdirWithFileTypes$1(directory, settings, callback); + return; + } + readdir$1(directory, settings, callback); +} +async$3.read = read$1; +function readdirWithFileTypes$1(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + callFailureCallback$1(callback, readdirError); + return; + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: common$5.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + })); + if (!settings.followSymbolicLinks) { + callSuccessCallback$1(callback, entries); + return; + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + rpl(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + callFailureCallback$1(callback, rplError); + return; + } + callSuccessCallback$1(callback, rplEntries); + }); + }); +} +async$3.readdirWithFileTypes = readdirWithFileTypes$1; +function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + done(null, entry); + return; + } + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + done(statError); + return; + } + done(null, entry); + return; + } + entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats); + done(null, entry); + }); + }; +} +function readdir$1(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + callFailureCallback$1(callback, readdirError); + return; + } + const tasks = names.map((name) => { + const path = common$5.joinPathSegments(directory, name, settings.pathSegmentSeparator); + return (done) => { + fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => { + if (error !== null) { + done(error); + return; + } + const entry = { + name, + path, + dirent: utils$8.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + done(null, entry); + }); + }; + }); + rpl(tasks, (rplError, entries) => { + if (rplError !== null) { + callFailureCallback$1(callback, rplError); + return; + } + callSuccessCallback$1(callback, entries); + }); + }); +} +async$3.readdir = readdir$1; +function callFailureCallback$1(callback, error) { + callback(error); +} +function callSuccessCallback$1(callback, result) { + callback(null, result); +} + +var sync$5 = {}; + +Object.defineProperty(sync$5, "__esModule", { value: true }); +sync$5.readdir = sync$5.readdirWithFileTypes = sync$5.read = void 0; +const fsStat$4 = out$1; +const constants_1 = constants; +const utils$7 = utils$9; +const common$4 = common$6; +function read(directory, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + return readdir(directory, settings); +} +sync$5.read = read; +function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); + return dirents.map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: common$4.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats); + } + catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + return entry; + }); +} +sync$5.readdirWithFileTypes = readdirWithFileTypes; +function readdir(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map((name) => { + const entryPath = common$4.joinPathSegments(directory, name, settings.pathSegmentSeparator); + const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils$7.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + return entry; + }); +} +sync$5.readdir = readdir; + +var settings$2 = {}; + +var fs$1 = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; + const fs = require$$0$2; + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync + }; + function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); + } + exports.createFileSystemAdapter = createFileSystemAdapter; +} (fs$1)); + +Object.defineProperty(settings$2, "__esModule", { value: true }); +const path$3 = g; +const fsStat$3 = out$1; +const fs = fs$1; +class Settings$1 { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$3.sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new fsStat$3.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +settings$2.default = Settings$1; + +Object.defineProperty(out$2, "__esModule", { value: true }); +out$2.Settings = out$2.scandirSync = out$2.scandir = void 0; +const async = async$3; +const sync$4 = sync$5; +const settings_1$2 = settings$2; +out$2.Settings = settings_1$2.default; +function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings$1(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback); +} +out$2.scandir = scandir; +function scandirSync(path, optionsOrSettings) { + const settings = getSettings$1(optionsOrSettings); + return sync$4.read(path, settings); +} +out$2.scandirSync = scandirSync; +function getSettings$1(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$2.default) { + return settingsOrOptions; + } + return new settings_1$2.default(settingsOrOptions); +} + +var queue = {exports: {}}; + +function reusify$1 (Constructor) { + var head = new Constructor(); + var tail = head; + + function get () { + var current = head; + + if (current.next) { + head = current.next; + } else { + head = new Constructor(); + tail = head; + } + + current.next = null; + + return current + } + + function release (obj) { + tail.next = obj; + tail = obj; + } + + return { + get: get, + release: release + } +} + +var reusify_1 = reusify$1; + +/* eslint-disable no-var */ + +var reusify = reusify_1; + +function fastqueue (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker; + worker = context; + context = null; + } + + if (concurrency < 1) { + throw new Error('fastqueue concurrency must be greater than 1') + } + + var cache = reusify(Task); + var queueHead = null; + var queueTail = null; + var _running = 0; + var errorHandler = null; + + var self = { + push: push, + drain: noop, + saturated: noop, + pause: pause, + paused: false, + concurrency: concurrency, + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop, + kill: kill, + killAndDrain: killAndDrain, + error: error + }; + + return self + + function running () { + return _running + } + + function pause () { + self.paused = true; + } + + function length () { + var current = queueHead; + var counter = 0; + + while (current) { + current = current.next; + counter++; + } + + return counter + } + + function getQueue () { + var current = queueHead; + var tasks = []; + + while (current) { + tasks.push(current.value); + current = current.next; + } + + return tasks + } + + function resume () { + if (!self.paused) return + self.paused = false; + for (var i = 0; i < self.concurrency; i++) { + _running++; + release(); + } + } + + function idle () { + return _running === 0 && self.length() === 0 + } + + function push (value, done) { + var current = cache.get(); + + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop; + current.errorHandler = errorHandler; + + if (_running === self.concurrency || self.paused) { + if (queueTail) { + queueTail.next = current; + queueTail = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + } else { + _running++; + worker.call(context, current.value, current.worked); + } + } + + function unshift (value, done) { + var current = cache.get(); + + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop; + + if (_running === self.concurrency || self.paused) { + if (queueHead) { + current.next = queueHead; + queueHead = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + } else { + _running++; + worker.call(context, current.value, current.worked); + } + } + + function release (holder) { + if (holder) { + cache.release(holder); + } + var next = queueHead; + if (next) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null; + } + queueHead = next.next; + next.next = null; + worker.call(context, next.value, next.worked); + if (queueTail === null) { + self.empty(); + } + } else { + _running--; + } + } else if (--_running === 0) { + self.drain(); + } + } + + function kill () { + queueHead = null; + queueTail = null; + self.drain = noop; + } + + function killAndDrain () { + queueHead = null; + queueTail = null; + self.drain(); + self.drain = noop; + } + + function error (handler) { + errorHandler = handler; + } +} + +function noop () {} + +function Task () { + this.value = null; + this.callback = noop; + this.next = null; + this.release = noop; + this.context = null; + this.errorHandler = null; + + var self = this; + + this.worked = function worked (err, result) { + var callback = self.callback; + var errorHandler = self.errorHandler; + var val = self.value; + self.value = null; + self.callback = noop; + if (self.errorHandler) { + errorHandler(err, val); + } + callback.call(self.context, err, result); + self.release(self); + }; +} + +function queueAsPromised (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker; + worker = context; + context = null; + } + + function asyncWrapper (arg, cb) { + worker.call(this, arg) + .then(function (res) { + cb(null, res); + }, cb); + } + + var queue = fastqueue(context, asyncWrapper, concurrency); + + var pushCb = queue.push; + var unshiftCb = queue.unshift; + + queue.push = push; + queue.unshift = unshift; + queue.drained = drained; + + return queue + + function push (value) { + var p = new Promise(function (resolve, reject) { + pushCb(value, function (err, result) { + if (err) { + reject(err); + return + } + resolve(result); + }); + }); + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop); + + return p + } + + function unshift (value) { + var p = new Promise(function (resolve, reject) { + unshiftCb(value, function (err, result) { + if (err) { + reject(err); + return + } + resolve(result); + }); + }); + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop); + + return p + } + + function drained () { + var previousDrain = queue.drain; + + var p = new Promise(function (resolve) { + queue.drain = function () { + previousDrain(); + resolve(); + }; + }); + + return p + } +} + +queue.exports = fastqueue; +queue.exports.promise = queueAsPromised; + +var common$3 = {}; + +Object.defineProperty(common$3, "__esModule", { value: true }); +common$3.joinPathSegments = common$3.replacePathSegmentSeparator = common$3.isAppliedFilter = common$3.isFatalError = void 0; +function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + return !settings.errorFilter(error); +} +common$3.isFatalError = isFatalError; +function isAppliedFilter(filter, value) { + return filter === null || filter(value); +} +common$3.isAppliedFilter = isAppliedFilter; +function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[/\\]/).join(separator); +} +common$3.replacePathSegmentSeparator = replacePathSegmentSeparator; +function joinPathSegments(a, b, separator) { + if (a === '') { + return b; + } + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +common$3.joinPathSegments = joinPathSegments; + +var reader$1 = {}; + +Object.defineProperty(reader$1, "__esModule", { value: true }); +const common$2 = common$3; +class Reader$1 { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common$2.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } +} +reader$1.default = Reader$1; + +Object.defineProperty(async$4, "__esModule", { value: true }); +const events_1 = require$$2; +const fsScandir$2 = out$2; +const fastq = queue.exports; +const common$1 = common$3; +const reader_1$4 = reader$1; +class AsyncReader extends reader_1$4.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir$2.scandir; + this._emitter = new events_1.EventEmitter(); + this._queue = fastq(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + get isDestroyed() { + return this._isDestroyed; + } + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on('entry', callback); + } + onError(callback) { + this._emitter.once('error', callback); + } + onEnd(callback) { + this._emitter.once('end', callback); + } + _pushToQueue(directory, base) { + const queueItem = { directory, base }; + this._queue.push(queueItem, (error) => { + if (error !== null) { + this._handleError(error); + } + }); + } + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + done(error, undefined); + return; + } + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + done(null, undefined); + }); + } + _handleError(error) { + if (this._isDestroyed || !common$1.isFatalError(this._settings, error)) { + return; + } + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit('error', error); + } + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common$1.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common$1.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common$1.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } +} +async$4.default = AsyncReader; + +Object.defineProperty(async$5, "__esModule", { value: true }); +const async_1$4 = async$4; +class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1$4.default(this._root, this._settings); + this._storage = []; + } + read(callback) { + this._reader.onError((error) => { + callFailureCallback(callback, error); + }); + this._reader.onEntry((entry) => { + this._storage.push(entry); + }); + this._reader.onEnd(() => { + callSuccessCallback(callback, this._storage); + }); + this._reader.read(); + } +} +async$5.default = AsyncProvider; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, entries) { + callback(null, entries); +} + +var stream$2 = {}; + +Object.defineProperty(stream$2, "__esModule", { value: true }); +const stream_1$5 = require$$0$1; +const async_1$3 = async$4; +class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1$3.default(this._root, this._settings); + this._stream = new stream_1$5.Readable({ + objectMode: true, + read: () => { }, + destroy: () => { + if (!this._reader.isDestroyed) { + this._reader.destroy(); + } + } + }); + } + read() { + this._reader.onError((error) => { + this._stream.emit('error', error); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } +} +stream$2.default = StreamProvider; + +var sync$3 = {}; + +var sync$2 = {}; + +Object.defineProperty(sync$2, "__esModule", { value: true }); +const fsScandir$1 = out$2; +const common = common$3; +const reader_1$3 = reader$1; +class SyncReader extends reader_1$3.default { + constructor() { + super(...arguments); + this._scandir = fsScandir$1.scandirSync; + this._storage = []; + this._queue = new Set(); + } + read() { + this._pushToQueue(this._root, this._settings.basePath); + this._handleQueue(); + return this._storage; + } + _pushToQueue(directory, base) { + this._queue.add({ directory, base }); + } + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.directory, item.base); + } + } + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + for (const entry of entries) { + this._handleEntry(entry, base); + } + } + catch (error) { + this._handleError(error); + } + } + _handleError(error) { + if (!common.isFatalError(this._settings, error)) { + return; + } + throw error; + } + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _pushToStorage(entry) { + this._storage.push(entry); + } +} +sync$2.default = SyncReader; + +Object.defineProperty(sync$3, "__esModule", { value: true }); +const sync_1$3 = sync$2; +class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync_1$3.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } +} +sync$3.default = SyncProvider; + +var settings$1 = {}; + +Object.defineProperty(settings$1, "__esModule", { value: true }); +const path$2 = g; +const fsScandir = out$2; +class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$2.sep); + this.fsScandirSettings = new fsScandir.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +settings$1.default = Settings; + +Object.defineProperty(out$3, "__esModule", { value: true }); +out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0; +const async_1$2 = async$5; +const stream_1$4 = stream$2; +const sync_1$2 = sync$3; +const settings_1$1 = settings$1; +out$3.Settings = settings_1$1.default; +function walk(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + return; + } + new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); +} +out$3.walk = walk; +function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync_1$2.default(directory, settings); + return provider.read(); +} +out$3.walkSync = walkSync; +function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream_1$4.default(directory, settings); + return provider.read(); +} +out$3.walkStream = walkStream; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$1.default) { + return settingsOrOptions; + } + return new settings_1$1.default(settingsOrOptions); +} + +var reader = {}; + +Object.defineProperty(reader, "__esModule", { value: true }); +const path$1 = g; +const fsStat$2 = out$1; +const utils$6 = utils$k; +class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat$2.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path$1.resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils$6.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) { + entry.stats = stats; + } + return entry; + } + _isFatalError(error) { + return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } +} +reader.default = Reader; + +var stream$1 = {}; + +Object.defineProperty(stream$1, "__esModule", { value: true }); +const stream_1$3 = require$$0$1; +const fsStat$1 = out$1; +const fsWalk$2 = out$3; +const reader_1$2 = reader; +class ReaderStream extends reader_1$2.default { + constructor() { + super(...arguments); + this._walkStream = fsWalk$2.walkStream; + this._stat = fsStat$1.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream_1$3.PassThrough({ objectMode: true }); + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options) + .then((entry) => { + if (entry !== null && options.entryFilter(entry)) { + stream.push(entry); + } + if (index === filepaths.length - 1) { + stream.end(); + } + done(); + }) + .catch(done); + }; + for (let i = 0; i < filepaths.length; i++) { + stream.write(i); + } + return stream; + } + _getEntry(filepath, pattern, options) { + return this._getStat(filepath) + .then((stats) => this._makeEntry(stats, pattern)) + .catch((error) => { + if (options.errorFilter(error)) { + return null; + } + throw error; + }); + } + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); + } +} +stream$1.default = ReaderStream; + +Object.defineProperty(async$6, "__esModule", { value: true }); +const fsWalk$1 = out$3; +const reader_1$1 = reader; +const stream_1$2 = stream$1; +class ReaderAsync extends reader_1$1.default { + constructor() { + super(...arguments); + this._walkAsync = fsWalk$1.walk; + this._readerStream = new stream_1$2.default(this._settings); + } + dynamic(root, options) { + return new Promise((resolve, reject) => { + this._walkAsync(root, options, (error, entries) => { + if (error === null) { + resolve(entries); + } + else { + reject(error); + } + }); + }); + } + async static(patterns, options) { + const entries = []; + const stream = this._readerStream.static(patterns, options); + // After #235, replace it with an asynchronous iterator. + return new Promise((resolve, reject) => { + stream.once('error', reject); + stream.on('data', (entry) => entries.push(entry)); + stream.once('end', () => resolve(entries)); + }); + } +} +async$6.default = ReaderAsync; + +var provider = {}; + +var deep = {}; + +var partial = {}; + +var matcher = {}; + +Object.defineProperty(matcher, "__esModule", { value: true }); +const utils$5 = utils$k; +class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + this._fillStorage(); + } + _fillStorage() { + /** + * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). + * So, before expand patterns with brace expansion into separated patterns. + */ + const patterns = utils$5.pattern.expandPatternsWithBraceExpansion(this._patterns); + for (const pattern of patterns) { + const segments = this._getPatternSegments(pattern); + const sections = this._splitSegmentsIntoSections(segments); + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + _getPatternSegments(pattern) { + const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map((part) => { + const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings); + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + return { + dynamic: true, + pattern: part, + patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern)); + } +} +matcher.default = Matcher; + +Object.defineProperty(partial, "__esModule", { value: true }); +const matcher_1 = matcher; +class PartialMatcher extends matcher_1.default { + match(filepath) { + const parts = filepath.split('/'); + const levels = parts.length; + const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + if (!pattern.complete && levels > section.length) { + return true; + } + const match = parts.every((part, index) => { + const segment = pattern.segments[index]; + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + if (!segment.dynamic && segment.pattern === part) { + return true; + } + return false; + }); + if (match) { + return true; + } + } + return false; + } +} +partial.default = PartialMatcher; + +Object.defineProperty(deep, "__esModule", { value: true }); +const utils$4 = utils$k; +const partial_1 = partial; +class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, matcher, negativeRe); + } + _getMatcher(patterns) { + return new partial_1.default(patterns, this._settings, this._micromatchOptions); + } + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern); + return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; + } + if (this._isSkippedSymbolicLink(entry)) { + return false; + } + const filepath = utils$4.path.removeLeadingDotSegment(entry.path); + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; + } + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) { + return false; + } + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split('/').length; + if (basePath === '') { + return entryPathDepth; + } + const basePathDepth = basePath.split('/').length; + return entryPathDepth - basePathDepth; + } + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils$4.pattern.matchAny(entryPath, patternsRe); + } +} +deep.default = DeepFilter; + +var entry$1 = {}; + +Object.defineProperty(entry$1, "__esModule", { value: true }); +const utils$3 = utils$k; +class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + getFilter(positive, negative) { + const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions); + const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions); + return (entry) => this._filter(entry, positiveRe, negativeRe); + } + _filter(entry, positiveRe, negativeRe) { + if (this._settings.unique && this._isDuplicateEntry(entry)) { + return false; + } + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; + } + if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { + return false; + } + const filepath = this._settings.baseNameMatch ? entry.name : entry.path; + const isDirectory = entry.dirent.isDirectory(); + const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(entry.path, negativeRe, isDirectory); + if (this._settings.unique && isMatched) { + this._createIndexRecord(entry); + } + return isMatched; + } + _isDuplicateEntry(entry) { + return this.index.has(entry.path); + } + _createIndexRecord(entry) { + this.index.set(entry.path, undefined); + } + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { + if (!this._settings.absolute) { + return false; + } + const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath); + return utils$3.pattern.matchAny(fullpath, patternsRe); + } + _isMatchToPatterns(entryPath, patternsRe, isDirectory) { + const filepath = utils$3.path.removeLeadingDotSegment(entryPath); + // Trying to match files and directories by patterns. + const isMatched = utils$3.pattern.matchAny(filepath, patternsRe); + // A pattern with a trailling slash can be used for directory matching. + // To apply such pattern, we need to add a tralling slash to the path. + if (!isMatched && isDirectory) { + return utils$3.pattern.matchAny(filepath + '/', patternsRe); + } + return isMatched; + } +} +entry$1.default = EntryFilter; + +var error = {}; + +Object.defineProperty(error, "__esModule", { value: true }); +const utils$2 = utils$k; +class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + getFilter() { + return (error) => this._isNonFatalError(error); + } + _isNonFatalError(error) { + return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + } +} +error.default = ErrorFilter; + +var entry = {}; + +Object.defineProperty(entry, "__esModule", { value: true }); +const utils$1 = utils$k; +class EntryTransformer { + constructor(_settings) { + this._settings = _settings; + } + getTransformer() { + return (entry) => this._transform(entry); + } + _transform(entry) { + let filepath = entry.path; + if (this._settings.absolute) { + filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils$1.path.unixify(filepath); + } + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += '/'; + } + if (!this._settings.objectMode) { + return filepath; + } + return Object.assign(Object.assign({}, entry), { path: filepath }); + } +} +entry.default = EntryTransformer; + +Object.defineProperty(provider, "__esModule", { value: true }); +const path = g; +const deep_1 = deep; +const entry_1 = entry$1; +const error_1 = error; +const entry_2 = entry; +class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error_1.default(this._settings); + this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry_2.default(this._settings); + } + _getRootDirectory(task) { + return path.resolve(this._settings.cwd, task.base); + } + _getReaderOptions(task) { + const basePath = task.base === '.' ? '' : task.base; + return { + basePath, + pathSegmentSeparator: '/', + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } +} +provider.default = Provider; + +Object.defineProperty(async$7, "__esModule", { value: true }); +const async_1$1 = async$6; +const provider_1$2 = provider; +class ProviderAsync extends provider_1$2.default { + constructor() { + super(...arguments); + this._reader = new async_1$1.default(this._settings); + } + async read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = await this.api(root, task, options); + return entries.map((entry) => options.transform(entry)); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +async$7.default = ProviderAsync; + +var stream = {}; + +Object.defineProperty(stream, "__esModule", { value: true }); +const stream_1$1 = require$$0$1; +const stream_2 = stream$1; +const provider_1$1 = provider; +class ProviderStream extends provider_1$1.default { + constructor() { + super(...arguments); + this._reader = new stream_2.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const source = this.api(root, task, options); + const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } }); + source + .once('error', (error) => destination.emit('error', error)) + .on('data', (entry) => destination.emit('data', options.transform(entry))) + .once('end', () => destination.emit('end')); + destination + .once('close', () => source.destroy()); + return destination; + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +stream.default = ProviderStream; + +var sync$1 = {}; + +var sync = {}; + +Object.defineProperty(sync, "__esModule", { value: true }); +const fsStat = out$1; +const fsWalk = out$3; +const reader_1 = reader; +class ReaderSync extends reader_1.default { + constructor() { + super(...arguments); + this._walkSync = fsWalk.walkSync; + this._statSync = fsStat.statSync; + } + dynamic(root, options) { + return this._walkSync(root, options); + } + static(patterns, options) { + const entries = []; + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + const entry = this._getEntry(filepath, pattern, options); + if (entry === null || !options.entryFilter(entry)) { + continue; + } + entries.push(entry); + } + return entries; + } + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); + } + catch (error) { + if (options.errorFilter(error)) { + return null; + } + throw error; + } + } + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); + } +} +sync.default = ReaderSync; + +Object.defineProperty(sync$1, "__esModule", { value: true }); +const sync_1$1 = sync; +const provider_1 = provider; +class ProviderSync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1$1.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = this.api(root, task, options); + return entries.map(options.transform); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +sync$1.default = ProviderSync; + +var settings = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; + const fs = require$$0$2; + const os = require$$0; + /** + * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. + * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 + */ + const CPU_COUNT = Math.max(os.cpus().length, 1); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + lstatSync: fs.lstatSync, + stat: fs.stat, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync + }; + class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + if (this.onlyDirectories) { + this.onlyFiles = false; + } + if (this.stats) { + this.objectMode = true; + } + } + _getValue(option, value) { + return option === undefined ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } + } + exports.default = Settings; +} (settings)); + +const taskManager = tasks; +const patternManager = patterns; +const async_1 = async$7; +const stream_1 = stream; +const sync_1 = sync$1; +const settings_1 = settings; +const utils = utils$k; +async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async_1.default, options); + const result = await Promise.all(works); + return utils.array.flatten(result); +} +// https://github.com/typescript-eslint/typescript-eslint/issues/60 +// eslint-disable-next-line no-redeclare +(function (FastGlob) { + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync_1.default, options); + return utils.array.flatten(works); + } + FastGlob.sync = sync; + function stream(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream_1.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + return utils.stream.merge(works); + } + FastGlob.stream = stream; + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = patternManager.transform([].concat(source)); + const settings = new settings_1.default(options); + return taskManager.generate(patterns, settings); + } + FastGlob.generateTasks = generateTasks; + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings_1.default(options); + return utils.pattern.isDynamicPattern(source, settings); + } + FastGlob.isDynamicPattern = isDynamicPattern; + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escape(source); + } + FastGlob.escapePath = escapePath; +})(FastGlob || (FastGlob = {})); +function getWorks(source, _Provider, options) { + const patterns = patternManager.transform([].concat(source)); + const settings = new settings_1.default(options); + const tasks = taskManager.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks.map(provider.read, provider); +} +function assertPatternsInput(input) { + const source = [].concat(input); + const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); + if (!isValidSource) { + throw new TypeError('Patterns must be a string (non empty) or an array of strings'); + } +} +var out = FastGlob; + +class SnapshotManager { + constructor(options) { + this.options = options; + this.summary = void 0; + this.extension = ".snap"; + this.clear(); + } + clear() { + this.summary = emptySummary(this.options); + } + add(result) { + addSnapshotResult(this.summary, result); + } + resolvePath(testPath) { + const resolver = this.options.resolveSnapshotPath || (() => { + return join( + join( + dirname(testPath), + "__snapshots__" + ), + `${basename(testPath)}${this.extension}` + ); + }); + return resolver(testPath, this.extension); + } +} +function emptySummary(options) { + const summary = { + added: 0, + failure: false, + filesAdded: 0, + filesRemoved: 0, + filesRemovedList: [], + filesUnmatched: 0, + filesUpdated: 0, + matched: 0, + total: 0, + unchecked: 0, + uncheckedKeysByFile: [], + unmatched: 0, + updated: 0, + didUpdate: options.updateSnapshot === "all" + }; + return summary; +} +function addSnapshotResult(summary, result) { + if (result.added) + summary.filesAdded++; + if (result.fileDeleted) + summary.filesRemoved++; + if (result.unmatched) + summary.filesUnmatched++; + if (result.updated) + summary.filesUpdated++; + summary.added += result.added; + summary.matched += result.matched; + summary.unchecked += result.unchecked; + if (result.uncheckedKeys && result.uncheckedKeys.length > 0) { + summary.uncheckedKeysByFile.push({ + filePath: result.filepath, + keys: result.uncheckedKeys + }); + } + summary.unmatched += result.unmatched; + summary.updated += result.updated; + summary.total += result.added + result.matched + result.unmatched + result.updated; +} + +function T(r){const t=/^\\\\\?\\/.test(r),n=/[^\u0000-\u0080]+/.test(r);return t||n?r:r.replace(/\\/g,"/")}function B(r,t){for(;;){const n=g.join(r,t);if(require$$0$2.existsSync(n))return T(n);const e=g.dirname(r);if(e===r)return;r=e;}}function G(r,t){t===void 0&&(t=!1);var n=r.length,e=0,i="",a=0,o=16,u=0,f=0,d=0,C=0,c=0;function y(s,m){for(var v=0,b=0;v=48&&h<=57)b=b*16+h-48;else if(h>=65&&h<=70)b=b*16+h-65+10;else if(h>=97&&h<=102)b=b*16+h-97+10;else break;e++,v++;}return v=n){s+=r.substring(m,e),c=2;break}var v=r.charCodeAt(e);if(v===34){s+=r.substring(m,e),e++;break}if(v===92){if(s+=r.substring(m,e),e++,e>=n){c=2;break}var b=r.charCodeAt(e++);switch(b){case 34:s+='"';break;case 92:s+="\\";break;case 47:s+="/";break;case 98:s+="\b";break;case 102:s+="\f";break;case 110:s+=` +`;break;case 114:s+="\r";break;case 116:s+=" ";break;case 117:var h=y(4,!0);h>=0?s+=String.fromCharCode(h):c=4;break;default:c=5;}m=e;continue}if(v>=0&&v<=31)if(P(v)){s+=r.substring(m,e),c=2;break}else c=6;e++;}return s}function S(){if(i="",c=0,a=e,f=u,C=d,e>=n)return a=n,o=17;var s=r.charCodeAt(e);if(U(s)){do e++,i+=String.fromCharCode(s),s=r.charCodeAt(e);while(U(s));return o=15}if(P(s))return e++,i+=String.fromCharCode(s),s===13&&r.charCodeAt(e)===10&&(e++,i+=` +`),u++,d=e,o=14;switch(s){case 123:return e++,o=1;case 125:return e++,o=2;case 91:return e++,o=3;case 93:return e++,o=4;case 58:return e++,o=6;case 44:return e++,o=5;case 34:return e++,i=_(),o=10;case 47:var m=e-1;if(r.charCodeAt(e+1)===47){for(e+=2;e=12&&s<=15);return s}return {setPosition:V,getPosition:function(){return e},scan:t?l:S,getToken:function(){return o},getTokenValue:function(){return i},getTokenOffset:function(){return a},getTokenLength:function(){return e-a},getTokenStartLine:function(){return f},getTokenStartCharacter:function(){return a-C},getTokenError:function(){return c}}}function U(r){return r===32||r===9||r===11||r===12||r===160||r===5760||r>=8192&&r<=8203||r===8239||r===8287||r===12288||r===65279}function P(r){return r===10||r===13||r===8232||r===8233}function j(r){return r>=48&&r<=57}var N;(function(r){r.DEFAULT={allowTrailingComma:!1};})(N||(N={}));function K(r,t,n){t===void 0&&(t=[]),n===void 0&&(n=N.DEFAULT);var e=null,i=[],a=[];function o(f){Array.isArray(i)?i.push(f):e!==null&&(i[e]=f);}var u={onObjectBegin:function(){var f={};o(f),a.push(i),i=f,e=null;},onObjectProperty:function(f){e=f;},onObjectEnd:function(){i=a.pop();},onArrayBegin:function(){var f=[];o(f),a.push(i),i=f,e=null;},onArrayEnd:function(){i=a.pop();},onLiteralValue:o,onError:function(f,d,C){t.push({error:f,offset:d,length:C});}};return Q(r,u,n),i[0]}function Q(r,t,n){n===void 0&&(n=N.DEFAULT);var e=G(r,!1);function i(p){return p?function(){return p(e.getTokenOffset(),e.getTokenLength(),e.getTokenStartLine(),e.getTokenStartCharacter())}:function(){return !0}}function a(p){return p?function(w){return p(w,e.getTokenOffset(),e.getTokenLength(),e.getTokenStartLine(),e.getTokenStartCharacter())}:function(){return !0}}var o=i(t.onObjectBegin),u=a(t.onObjectProperty),f=i(t.onObjectEnd),d=i(t.onArrayBegin),C=i(t.onArrayEnd),c=a(t.onLiteralValue),y=a(t.onSeparator),V=i(t.onComment),$=a(t.onError),_=n&&n.disallowComments,S=n&&n.allowTrailingComma;function k(){for(;;){var p=e.scan();switch(e.getTokenError()){case 4:l(14);break;case 5:l(15);break;case 3:l(13);break;case 1:_||l(11);break;case 2:l(12);break;case 6:l(16);break}switch(p){case 12:case 13:_?l(10):V();break;case 16:l(1);break;case 15:case 14:break;default:return p}}}function l(p,w,L){if(w===void 0&&(w=[]),L===void 0&&(L=[]),$(p),w.length+L.length>0)for(var D=e.getToken();D!==17;){if(w.indexOf(D)!==-1){k();break}else if(L.indexOf(D)!==-1)break;D=k();}}function s(p){var w=e.getTokenValue();return p?c(w):u(w),k(),!0}function m(){switch(e.getToken()){case 11:var p=e.getTokenValue(),w=Number(p);isNaN(w)&&(l(2),w=0),c(w);break;case 7:c(null);break;case 8:c(!0);break;case 9:c(!1);break;default:return !1}return k(),!0}function v(){return e.getToken()!==10?(l(3,[],[2,5]),!1):(s(!1),e.getToken()===6?(y(":"),k(),F()||l(4,[],[2,5])):l(5,[],[2,5]),!0)}function b(){o(),k();for(var p=!1;e.getToken()!==2&&e.getToken()!==17;){if(e.getToken()===5){if(p||l(4,[],[]),y(","),k(),e.getToken()===2&&S)break}else p&&l(6,[],[]);v()||l(4,[],[2,5]),p=!0;}return f(),e.getToken()!==2?l(7,[2],[]):k(),!0}function h(){d(),k();for(var p=!1;e.getToken()!==4&&e.getToken()!==17;){if(e.getToken()===5){if(p||l(4,[],[]),y(","),k(),e.getToken()===4&&S)break}else p&&l(6,[],[]);F()||l(4,[],[4,5]),p=!0;}return C(),e.getToken()!==4?l(8,[4],[]):k(),!0}function F(){switch(e.getToken()){case 3:return h();case 1:return b();case 10:return s(!0);default:return m()}}return k(),e.getToken()===17?n.allowEmptyContent?!0:(l(4,[],[]),!1):F()?(e.getToken()!==17&&l(9,[],[]),!0):(l(4,[],[]),!1)}var X=K;const W=/^\.{1,2}(\/.*)?$/,J=r=>T(W.test(r)?r:`./${r}`),{existsSync:E}=require$$0$2,Y=r=>{try{return JSON.parse(r)}catch{}},Z=()=>{const{findPnpApi:r}=H;return r&&r(process.cwd())};function I(r){const t=Y(require$$0$2.readFileSync(r,"utf8"));return g.join(r,"..",t&&"tsconfig"in t?t.tsconfig:"tsconfig.json")}function x(r,t){let n=r;if(n===".."&&(n+="/tsconfig.json"),n.startsWith(".")){let a=g.resolve(t,n);if(E(a)&&require$$0$2.statSync(a).isFile()||!a.endsWith(".json")&&(a+=".json",E(a)))return a;throw new Error(`File '${r}' not found.`)}const e=Z();if(e){const{resolveRequest:a}=e,[o,u]=r.split("/"),f=o.startsWith("@")?`${o}/${u}`:o;try{if(f===r){const d=a(g.join(f,"package.json"),t);if(d){const C=I(d);if(E(C))return C}}else try{return a(r,t,{extensions:[".json"]})}catch{return a(g.join(r,"tsconfig.json"),t)}}catch{}}let i=B(t,g.join("node_modules",n));if(i){if(require$$0$2.statSync(i).isDirectory()){const a=g.join(i,"package.json");if(E(a)?i=I(a):i=g.join(i,"tsconfig.json"),E(i))return i}else if(i.endsWith(".json"))return i}if(!n.endsWith(".json")&&(n+=".json",i=B(t,g.join("node_modules",n)),i))return i;throw new Error(`File '${r}' not found.`)}var ee=Object.defineProperty,re=Object.defineProperties,ne=Object.getOwnPropertyDescriptors,R=Object.getOwnPropertySymbols,te=Object.prototype.hasOwnProperty,ae=Object.prototype.propertyIsEnumerable,q=(r,t,n)=>t in r?ee(r,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[t]=n,A=(r,t)=>{for(var n in t||(t={}))te.call(t,n)&&q(r,n,t[n]);if(R)for(var n of R(t))ae.call(t,n)&&q(r,n,t[n]);return r},oe=(r,t)=>re(r,ne(t));function M(r){var t;let n;try{n=require$$0$2.realpathSync(r);}catch{throw new Error(`Cannot resolve tsconfig at path: ${r}`)}const e=g.dirname(n),i=require$$0$2.readFileSync(n,"utf8").trim();let a={};if(i&&(a=X(i),!a||typeof a!="object"))throw new SyntaxError(`Failed to parse tsconfig at: ${r}`);if(a.extends){const o=x(a.extends,e),u=M(o);if(delete u.references,(t=u.compilerOptions)!=null&&t.baseUrl){const{compilerOptions:d}=u;d.baseUrl=g.relative(e,g.join(g.dirname(o),d.baseUrl))||"./";}u.files&&(u.files=u.files.map(d=>g.relative(e,g.join(g.dirname(o),d)))),u.include&&(u.include=u.include.map(d=>g.relative(e,g.join(g.dirname(o),d)))),delete a.extends;const f=oe(A(A({},u),a),{compilerOptions:A(A({},u.compilerOptions),a.compilerOptions)});u.watchOptions&&(f.watchOptions=A(A({},u.watchOptions),a.watchOptions)),a=f;}if(a.compilerOptions){const{compilerOptions:o}=a;o.baseUrl&&(o.baseUrl=J(o.baseUrl)),o.outDir&&(Array.isArray(a.exclude)||(a.exclude=[]),a.exclude.push(o.outDir),o.outDir=J(o.outDir));}if(a.files&&(a.files=a.files.map(J)),a.include&&(a.include=a.include.map(T)),a.watchOptions){const{watchOptions:o}=a;o.excludeDirectories&&(o.excludeDirectories=o.excludeDirectories.map(u=>T(g.resolve(e,u))));}return a}function ie(r=process.cwd(),t="tsconfig.json"){const n=B(r,t);if(!n)return null;const e=M(n);return {path:n,config:e}} + +const __dirname = url.fileURLToPath(new URL(".", import.meta.url)); +const newLineRegExp = /\r?\n/; +const errCodeRegExp = /error TS(?\d+)/; +async function makeTscErrorInfo(errInfo) { + var _a; + const [errFilePathPos = "", ...errMsgRawArr] = errInfo.split(":"); + if (!errFilePathPos || errMsgRawArr.length === 0 || errMsgRawArr.join("").length === 0) + return ["unknown filepath", null]; + const errMsgRaw = errMsgRawArr.join("").trim(); + const [errFilePath, errPos] = errFilePathPos.slice(0, -1).split("("); + if (!errFilePath || !errPos) + return ["unknown filepath", null]; + const [errLine, errCol] = errPos.split(","); + if (!errLine || !errCol) + return [errFilePath, null]; + const execArr = errCodeRegExp.exec(errMsgRaw); + if (!execArr) + return [errFilePath, null]; + const errCodeStr = ((_a = execArr.groups) == null ? void 0 : _a.errCode) ?? ""; + if (!errCodeStr) + return [errFilePath, null]; + const line = Number(errLine); + const col = Number(errCol); + const errCode = Number(errCodeStr); + return [ + errFilePath, + { + filePath: errFilePath, + errCode, + line, + column: col, + errMsg: errMsgRaw.slice(`error TS${errCode} `.length) + } + ]; +} +async function getTsconfig(root, config) { + var _a; + const tempConfigPath = join(root, "tsconfig.temp.json"); + const configName = ((_a = config.tsconfig) == null ? void 0 : _a.includes("jsconfig.json")) ? "jsconfig.json" : void 0; + const tsconfig = ie(config.tsconfig || root, configName); + if (!tsconfig) + throw new Error("no tsconfig.json found"); + try { + const tmpTsConfig = { ...tsconfig.config }; + tmpTsConfig.compilerOptions = tmpTsConfig.compilerOptions || {}; + tmpTsConfig.compilerOptions.emitDeclarationOnly = false; + tmpTsConfig.compilerOptions.incremental = true; + tmpTsConfig.compilerOptions.tsBuildInfoFile = join( + __dirname, + "tsconfig.tmp.tsbuildinfo" + ); + const tsconfigFinalContent = JSON.stringify(tmpTsConfig, null, 2); + await writeFile(tempConfigPath, tsconfigFinalContent); + return { path: tempConfigPath, config: tmpTsConfig }; + } catch (err) { + throw new Error("failed to write tsconfig.temp.json", { cause: err }); + } +} +async function getRawErrsMapFromTsCompile(tscErrorStdout) { + const rawErrsMap = /* @__PURE__ */ new Map(); + const infos = await Promise.all( + tscErrorStdout.split(newLineRegExp).reduce((prev, next) => { + if (!next) + return prev; + else if (!next.startsWith(" ")) + prev.push(next); + else + prev[prev.length - 1] += ` +${next}`; + return prev; + }, []).map((errInfoLine) => makeTscErrorInfo(errInfoLine)) + ); + infos.forEach(([errFilePath, errInfo]) => { + var _a; + if (!errInfo) + return; + if (!rawErrsMap.has(errFilePath)) + rawErrsMap.set(errFilePath, [errInfo]); + else + (_a = rawErrsMap.get(errFilePath)) == null ? void 0 : _a.push(errInfo); + }); + return rawErrsMap; +} + +const createIndexMap = (source) => { + const map = /* @__PURE__ */ new Map(); + let index = 0; + let line = 1; + let column = 1; + for (const char of source) { + map.set(`${line}:${column}`, index++); + if (char === "\n" || char === "\r\n") { + line++; + column = 0; + } else { + column++; + } + } + return map; +}; + +async function collectTests(ctx, filepath) { + const request = await ctx.vitenode.transformRequest(filepath); + if (!request) + return null; + const ast = parse$4(request.code, { + ecmaVersion: "latest", + allowAwaitOutsideFunction: true + }); + const testFilepath = relative(ctx.config.root, filepath); + const file = { + filepath, + type: "suite", + id: generateHash(testFilepath), + name: testFilepath, + mode: "run", + tasks: [], + start: ast.start, + end: ast.end + }; + const definitions = []; + const getName = (callee) => { + var _a, _b, _c; + if (!callee) + return null; + if (callee.type === "Identifier") + return callee.name; + if (callee.type === "MemberExpression") { + if ((_b = (_a = callee.object) == null ? void 0 : _a.name) == null ? void 0 : _b.startsWith("__vite_ssr_")) + return getName(callee.property); + return getName((_c = callee.object) == null ? void 0 : _c.property); + } + return null; + }; + ancestor(ast, { + CallExpression(node) { + var _a; + const { callee } = node; + const name = getName(callee); + if (!name) + return; + if (!["it", "test", "describe", "suite"].includes(name)) + return; + const { arguments: [{ value: message }] } = node; + const property = (_a = callee == null ? void 0 : callee.property) == null ? void 0 : _a.name; + let mode = !property || property === name ? "run" : property; + if (!["run", "skip", "todo", "only", "skipIf", "runIf"].includes(mode)) + throw new Error(`${name}.${mode} syntax is not supported when testing types`); + if (mode === "skipIf" || mode === "runIf") + mode = "skip"; + definitions.push({ + start: node.start, + end: node.end, + name: message, + type: name === "it" || name === "test" ? "test" : "suite", + mode + }); + } + }); + let lastSuite = file; + const updateLatestSuite = (index) => { + const suite = lastSuite; + while (lastSuite !== file && lastSuite.end < index) + lastSuite = suite.suite; + return lastSuite; + }; + definitions.sort((a, b) => a.start - b.start).forEach((definition) => { + const latestSuite = updateLatestSuite(definition.start); + let mode = definition.mode; + if (latestSuite.mode !== "run") + mode = latestSuite.mode; + if (definition.type === "suite") { + const task2 = { + type: definition.type, + id: "", + suite: latestSuite, + file, + tasks: [], + mode, + name: definition.name, + end: definition.end, + start: definition.start, + meta: { + typecheck: true + } + }; + definition.task = task2; + latestSuite.tasks.push(task2); + lastSuite = task2; + return; + } + const task = { + type: definition.type, + id: "", + suite: latestSuite, + file, + mode, + context: {}, + name: definition.name, + end: definition.end, + start: definition.start, + meta: { + typecheck: true + } + }; + definition.task = task; + latestSuite.tasks.push(task); + }); + calculateSuiteHash(file); + const hasOnly = someTasksAreOnly(file); + interpretTaskModes(file, ctx.config.testNamePattern, hasOnly, false, ctx.config.allowOnly); + return { + file, + parsed: request.code, + filepath, + map: request.map, + definitions + }; +} + +class TypeCheckError extends Error { + constructor(message, stacks) { + super(message); + this.message = message; + this.stacks = stacks; + this.name = "TypeCheckError"; + } +} +class Typechecker { + constructor(ctx, files) { + this.ctx = ctx; + this.files = files; + this._result = { + files: [], + sourceErrors: [] + }; + this._tests = {}; + } + onParseStart(fn) { + this._onParseStart = fn; + } + onParseEnd(fn) { + this._onParseEnd = fn; + } + onWatcherRerun(fn) { + this._onWatcherRerun = fn; + } + async collectFileTests(filepath) { + return collectTests(this.ctx, filepath); + } + getFiles() { + return this.files.filter((filename) => { + const extension = extname(filename); + return extension !== ".js" || this.allowJs; + }); + } + async collectTests() { + const tests = (await Promise.all( + this.getFiles().map((filepath) => this.collectFileTests(filepath)) + )).reduce((acc, data) => { + if (!data) + return acc; + acc[data.filepath] = data; + return acc; + }, {}); + this._tests = tests; + return tests; + } + async prepareResults(output) { + const typeErrors = await this.parseTscLikeOutput(output); + const testFiles = new Set(this.getFiles()); + if (!this._tests) + this._tests = await this.collectTests(); + const sourceErrors = []; + const files = []; + testFiles.forEach((path) => { + const { file, definitions, map, parsed } = this._tests[path]; + const errors = typeErrors.get(path); + files.push(file); + if (!errors) + return; + const sortedDefinitions = [...definitions.sort((a, b) => b.start - a.start)]; + const mapConsumer = map && new SourceMapConsumer(map); + const indexMap = createIndexMap(parsed); + const markFailed = (task) => { + task.result = { + state: task.mode === "run" || task.mode === "only" ? "fail" : task.mode + }; + if (task.suite) + markFailed(task.suite); + }; + errors.forEach(({ error, originalError }) => { + var _a; + const originalPos = (mapConsumer == null ? void 0 : mapConsumer.generatedPositionFor({ + line: originalError.line, + column: originalError.column, + source: path + })) || originalError; + const index = indexMap.get(`${originalPos.line}:${originalPos.column}`); + const definition = index != null && sortedDefinitions.find((def) => def.start <= index && def.end >= index); + const suite = definition ? definition.task : file; + const state = suite.mode === "run" || suite.mode === "only" ? "fail" : suite.mode; + const errors2 = ((_a = suite.result) == null ? void 0 : _a.errors) || []; + suite.result = { + state, + errors: errors2 + }; + errors2.push(error); + if (state === "fail" && suite.suite) + markFailed(suite.suite); + }); + }); + typeErrors.forEach((errors, path) => { + if (!testFiles.has(path)) + sourceErrors.push(...errors.map(({ error }) => error)); + }); + return { + files, + sourceErrors + }; + } + async parseTscLikeOutput(output) { + const errorsMap = await getRawErrsMapFromTsCompile(output); + const typesErrors = /* @__PURE__ */ new Map(); + errorsMap.forEach((errors, path) => { + const filepath = resolve(this.ctx.config.root, path); + const suiteErrors = errors.map((info) => { + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + const error = new TypeCheckError(info.errMsg, [ + { + file: filepath, + line: info.line, + column: info.column, + method: "" + } + ]); + Error.stackTraceLimit = limit; + return { + originalError: info, + error + }; + }); + typesErrors.set(filepath, suiteErrors); + }); + return typesErrors; + } + async clear() { + if (this.tempConfigPath) + await rm(this.tempConfigPath, { force: true }); + } + async stop() { + var _a; + await this.clear(); + (_a = this.process) == null ? void 0 : _a.kill(); + } + async ensurePackageInstalled(root, checker) { + if (checker !== "tsc" && checker !== "vue-tsc") + return; + const packageName = checker === "tsc" ? "typescript" : "vue-tsc"; + await ensurePackageInstalled(packageName, root); + } + async prepare() { + const { root, typecheck } = this.ctx.config; + await this.ensurePackageInstalled(root, typecheck.checker); + const { config, path } = await getTsconfig(root, typecheck); + this.tempConfigPath = path; + this.allowJs = typecheck.allowJs || config.allowJs || false; + } + async start() { + var _a, _b, _c; + if (!this.tempConfigPath) + throw new Error("tsconfig was not initialized"); + const { root, watch, typecheck } = this.ctx.config; + const args = ["--noEmit", "--pretty", "false", "-p", this.tempConfigPath]; + if (watch) + args.push("--watch"); + if (typecheck.allowJs) + args.push("--allowJs", "--checkJs"); + let output = ""; + const child = execa(typecheck.checker, args, { + cwd: root, + stdout: "pipe", + reject: false + }); + this.process = child; + await ((_a = this._onParseStart) == null ? void 0 : _a.call(this)); + let rerunTriggered = false; + (_b = child.stdout) == null ? void 0 : _b.on("data", (chunk) => { + var _a2; + output += chunk; + if (!watch) + return; + if (output.includes("File change detected") && !rerunTriggered) { + (_a2 = this._onWatcherRerun) == null ? void 0 : _a2.call(this); + this._result.sourceErrors = []; + this._result.files = []; + this._tests = null; + rerunTriggered = true; + } + if (/Found \w+ errors*. Watching for/.test(output)) { + rerunTriggered = false; + this.prepareResults(output).then((result) => { + var _a3; + this._result = result; + (_a3 = this._onParseEnd) == null ? void 0 : _a3.call(this, result); + }); + output = ""; + } + }); + if (!watch) { + await child; + this._result = await this.prepareResults(output); + await ((_c = this._onParseEnd) == null ? void 0 : _c.call(this, this._result)); + } + } + getResult() { + return this._result; + } + getTestFiles() { + return Object.values(this._tests || {}).map((i) => i.file); + } + getTestPacks() { + return Object.values(this._tests || {}).map((i) => [i.file.id, void 0]); + } +} + +const workerPath = url.pathToFileURL(resolve(distDir, "./worker.js")).href; +const loaderPath = url.pathToFileURL(resolve(distDir, "./loader.js")).href; +const suppressLoaderWarningsPath = resolve(rootDir, "./suppress-warnings.cjs"); +function createPool(ctx) { + var _a, _b, _c; + const threadsCount = ctx.config.watch ? Math.max(Math.floor(cpus().length / 2), 1) : Math.max(cpus().length - 1, 1); + const maxThreads = ctx.config.maxThreads ?? threadsCount; + const minThreads = ctx.config.minThreads ?? threadsCount; + const conditions = ((_a = ctx.server.config.resolve.conditions) == null ? void 0 : _a.flatMap((c) => ["--conditions", c])) || []; + const options = { + filename: workerPath, + useAtomics: false, + maxThreads, + minThreads, + execArgv: ctx.config.deps.registerNodeLoader ? [ + "--require", + suppressLoaderWarningsPath, + "--experimental-loader", + loaderPath, + ...conditions + ] : conditions + }; + if (ctx.config.isolate) { + options.isolateWorkers = true; + options.concurrentTasksPerWorker = 1; + } + if (!ctx.config.threads) { + options.concurrentTasksPerWorker = 1; + options.maxThreads = 1; + options.minThreads = 1; + } + (_c = (_b = ctx.coverageProvider) == null ? void 0 : _b.onBeforeFilesRun) == null ? void 0 : _c.call(_b); + options.env = { + TEST: "true", + VITEST: "true", + NODE_ENV: ctx.config.mode || "test", + VITEST_MODE: ctx.config.watch ? "WATCH" : "RUN", + ...process.env, + ...ctx.config.env + }; + const pool = new Tinypool(options); + const runWithFiles = (name) => { + let id = 0; + async function runFiles(config, files, invalidates = []) { + ctx.state.clearFiles(files); + const { workerPort, port } = createChannel(ctx); + const workerId = ++id; + const data = { + port: workerPort, + config, + files, + invalidates, + workerId + }; + try { + await pool.run(data, { transferList: [workerPort], name }); + } finally { + port.close(); + workerPort.close(); + } + } + const Sequencer = ctx.config.sequence.sequencer; + const sequencer = new Sequencer(ctx); + return async (files, invalidates) => { + const config = ctx.getSerializableConfig(); + if (config.shard) + files = await sequencer.shard(files); + files = await sequencer.sort(files); + if (!ctx.config.threads) { + await runFiles(config, files); + } else { + const results = await Promise.allSettled(files.map((file) => runFiles(config, [file], invalidates))); + const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason); + if (errors.length > 0) + throw new AggregateErrorPonyfill(errors, "Errors occurred while running tests. For more information, see serialized error."); + } + }; + }; + return { + runTests: runWithFiles("run"), + close: async () => { + } + }; +} +function createChannel(ctx) { + const channel = new MessageChannel(); + const port = channel.port2; + const workerPort = channel.port1; + createBirpc( + { + onWorkerExit(code) { + process.exit(code || 1); + }, + snapshotSaved(snapshot) { + ctx.snapshot.add(snapshot); + }, + resolveSnapshotPath(testPath) { + return ctx.snapshot.resolvePath(testPath); + }, + async getSourceMap(id, force) { + if (force) { + const mod = ctx.server.moduleGraph.getModuleById(id); + if (mod) + ctx.server.moduleGraph.invalidateModule(mod); + } + const r = await ctx.vitenode.transformRequest(id); + return r == null ? void 0 : r.map; + }, + fetch(id) { + return ctx.vitenode.fetchModule(id); + }, + resolveId(id, importer) { + return ctx.vitenode.resolveId(id, importer); + }, + onPathsCollected(paths) { + ctx.state.collectPaths(paths); + ctx.report("onPathsCollected", paths); + }, + onCollected(files) { + ctx.state.collectFiles(files); + ctx.report("onCollected", files); + }, + onAfterSuiteRun(meta) { + var _a; + (_a = ctx.coverageProvider) == null ? void 0 : _a.onAfterSuiteRun(meta); + }, + onTaskUpdate(packs) { + ctx.state.updateTasks(packs); + ctx.report("onTaskUpdate", packs); + }, + onUserConsoleLog(log) { + ctx.state.updateUserLog(log); + ctx.report("onUserConsoleLog", log); + }, + onUnhandledRejection(err) { + ctx.state.catchError(err, "Unhandled Rejection"); + }, + onFinished(files) { + ctx.report("onFinished", files, ctx.state.getUnhandledErrors()); + } + }, + { + post(v) { + port.postMessage(v); + }, + on(fn) { + port.on("message", fn); + } + } + ); + return { workerPort, port }; +} + +const F_RIGHT = "\u2192"; +const F_DOWN = "\u2193"; +const F_DOWN_RIGHT = "\u21B3"; +const F_POINTER = "\u276F"; +const F_DOT = "\xB7"; +const F_CHECK = "\u2713"; +const F_CROSS = "\xD7"; +const F_LONG_DASH = "\u23AF"; + +const spinnerMap = /* @__PURE__ */ new WeakMap(); +const hookSpinnerMap = /* @__PURE__ */ new WeakMap(); +const pointer = c.yellow(F_POINTER); +const skipped = c.dim(c.gray(F_DOWN)); +function getCols(delta = 0) { + var _a; + let length = (_a = process.stdout) == null ? void 0 : _a.columns; + if (!length || isNaN(length)) + length = 30; + return Math.max(length + delta, 0); +} +function divider(text, left, right) { + const cols = getCols(); + if (text) { + const textLength = stripAnsi(text).length; + if (left == null && right != null) { + left = cols - textLength - right; + } else { + left = left ?? Math.floor((cols - textLength) / 2); + right = cols - textLength - left; + } + left = Math.max(0, left); + right = Math.max(0, right); + return `${F_LONG_DASH.repeat(left)}${text}${F_LONG_DASH.repeat(right)}`; + } + return F_LONG_DASH.repeat(cols); +} +function formatTestPath(root, path) { + var _a; + if (isAbsolute(path)) + path = relative(root, path); + const dir = dirname(path); + const ext = ((_a = path.match(/(\.(spec|test)\.[cm]?[tj]sx?)$/)) == null ? void 0 : _a[0]) || ""; + const base = basename(path, ext); + return slash$1(c.dim(`${dir}/`) + c.bold(base)) + c.dim(ext); +} +function renderSnapshotSummary(rootDir, snapshots) { + const summary = []; + if (snapshots.added) + summary.push(c.bold(c.green(`${snapshots.added} written`))); + if (snapshots.unmatched) + summary.push(c.bold(c.red(`${snapshots.unmatched} failed`))); + if (snapshots.updated) + summary.push(c.bold(c.green(`${snapshots.updated} updated `))); + if (snapshots.filesRemoved) { + if (snapshots.didUpdate) + summary.push(c.bold(c.green(`${snapshots.filesRemoved} files removed `))); + else + summary.push(c.bold(c.yellow(`${snapshots.filesRemoved} files obsolete `))); + } + if (snapshots.filesRemovedList && snapshots.filesRemovedList.length) { + const [head, ...tail] = snapshots.filesRemovedList; + summary.push(`${c.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, head)}`); + tail.forEach((key) => { + summary.push(` ${c.gray(F_DOT)} ${formatTestPath(rootDir, key)}`); + }); + } + if (snapshots.unchecked) { + if (snapshots.didUpdate) + summary.push(c.bold(c.green(`${snapshots.unchecked} removed`))); + else + summary.push(c.bold(c.yellow(`${snapshots.unchecked} obsolete`))); + snapshots.uncheckedKeysByFile.forEach((uncheckedFile) => { + summary.push(`${c.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, uncheckedFile.filePath)}`); + uncheckedFile.keys.forEach((key) => summary.push(` ${c.gray(F_DOT)} ${key}`)); + }); + } + return summary; +} +function countTestErrors(tasks) { + return tasks.reduce((c2, i) => { + var _a, _b; + return c2 + (((_b = (_a = i.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.length) || 0); + }, 0); +} +function getStateString(tasks, name = "tests", showTotal = true) { + if (tasks.length === 0) + return c.dim(`no ${name}`); + const passed = tasks.filter((i) => { + var _a; + return ((_a = i.result) == null ? void 0 : _a.state) === "pass"; + }); + const failed = tasks.filter((i) => { + var _a; + return ((_a = i.result) == null ? void 0 : _a.state) === "fail"; + }); + const skipped2 = tasks.filter((i) => i.mode === "skip"); + const todo = tasks.filter((i) => i.mode === "todo"); + return [ + failed.length ? c.bold(c.red(`${failed.length} failed`)) : null, + passed.length ? c.bold(c.green(`${passed.length} passed`)) : null, + skipped2.length ? c.yellow(`${skipped2.length} skipped`) : null, + todo.length ? c.gray(`${todo.length} todo`) : null + ].filter(Boolean).join(c.dim(" | ")) + (showTotal ? c.gray(` (${tasks.length})`) : ""); +} +function getStateSymbol(task) { + if (task.mode === "skip" || task.mode === "todo") + return skipped; + if (!task.result) + return c.gray("\xB7"); + if (task.result.state === "run") { + if (task.type === "suite") + return pointer; + let spinner = spinnerMap.get(task); + if (!spinner) { + spinner = elegantSpinner(); + spinnerMap.set(task, spinner); + } + return c.yellow(spinner()); + } + if (task.result.state === "pass") { + return task.type === "benchmark" ? c.green(F_DOT) : c.green(F_CHECK); + } + if (task.result.state === "fail") { + return task.type === "suite" ? pointer : c.red(F_CROSS); + } + return " "; +} +function getHookStateSymbol(task, hookName) { + var _a, _b; + const state = (_b = (_a = task.result) == null ? void 0 : _a.hooks) == null ? void 0 : _b[hookName]; + if (state && state === "run") { + let spinnerMap2 = hookSpinnerMap.get(task); + if (!spinnerMap2) { + spinnerMap2 = /* @__PURE__ */ new Map(); + hookSpinnerMap.set(task, spinnerMap2); + } + let spinner = spinnerMap2.get(hookName); + if (!spinner) { + spinner = elegantSpinner(); + spinnerMap2.set(hookName, spinner); + } + return c.yellow(spinner()); + } +} +const spinnerFrames = process.platform === "win32" ? ["-", "\\", "|", "/"] : ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"]; +function elegantSpinner() { + let index = 0; + return () => { + index = ++index % spinnerFrames.length; + return spinnerFrames[index]; + }; +} +function formatTimeString(date) { + return date.toTimeString().split(" ")[0]; +} +function formatProjectName(name, suffix = " ") { + if (!name) + return ""; + const index = name.split("").reduce((acc, v, idx) => acc + v.charCodeAt(0) + idx, 0); + const colors = [ + c.blue, + c.yellow, + c.cyan, + c.green, + c.magenta + ]; + return colors[index % colors.length](`|${name}|`) + suffix; +} + +var _a; +const BADGE_PADDING = " "; +const HELP_HINT = `${c.dim("press ")}${c.bold("h")}${c.dim(" to show help")}`; +const HELP_UPDATE_SNAP = c.dim("press ") + c.bold(c.yellow("u")) + c.dim(" to update snapshot"); +const HELP_QUITE = `${c.dim("press ")}${c.bold("q")}${c.dim(" to quit")}`; +const WAIT_FOR_CHANGE_PASS = ` +${c.bold(c.inverse(c.green(" PASS ")))}${c.green(" Waiting for file changes...")}`; +const WAIT_FOR_CHANGE_FAIL = ` +${c.bold(c.inverse(c.red(" FAIL ")))}${c.red(" Tests failed. Watching for file changes...")}`; +const LAST_RUN_LOG_TIMEOUT = 1500; +class BaseReporter { + constructor() { + this.start = 0; + this.end = 0; + this.isTTY = isNode && ((_a = process.stdout) == null ? void 0 : _a.isTTY) && !process.env.CI; + this.ctx = void 0; + this._filesInWatchMode = /* @__PURE__ */ new Map(); + this._lastRunTimeout = 0; + this._lastRunCount = 0; + this._timeStart = new Date(); + this.registerUnhandledRejection(); + } + get mode() { + return this.ctx.config.mode; + } + onInit(ctx) { + this.ctx = ctx; + ctx.logger.printBanner(); + this.start = performance.now(); + } + relative(path) { + return relativePath(this.ctx.config.root, path); + } + async onFinished(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) { + this.end = performance.now(); + await this.reportSummary(files); + if (errors.length) { + if (!this.ctx.config.dangerouslyIgnoreUnhandledErrors) + process.exitCode = 1; + await this.ctx.logger.printUnhandledErrors(errors); + } + } + onTaskUpdate(packs) { + var _a2, _b, _c, _d; + if (this.isTTY) + return; + const logger = this.ctx.logger; + for (const pack of packs) { + const task = this.ctx.state.idMap.get(pack[0]); + if (task && "filepath" in task && ((_a2 = task.result) == null ? void 0 : _a2.state) && ((_b = task.result) == null ? void 0 : _b.state) !== "run") { + const tests = getTests(task); + const failed = tests.filter((t) => { + var _a3; + return ((_a3 = t.result) == null ? void 0 : _a3.state) === "fail"; + }); + const skipped = tests.filter((t) => t.mode === "skip" || t.mode === "todo"); + let state = c.dim(`${tests.length} test${tests.length > 1 ? "s" : ""}`); + if (failed.length) + state += ` ${c.dim("|")} ${c.red(`${failed.length} failed`)}`; + if (skipped.length) + state += ` ${c.dim("|")} ${c.yellow(`${skipped.length} skipped`)}`; + let suffix = c.dim(" (") + state + c.dim(")"); + if (task.result.duration) { + const color = task.result.duration > this.ctx.config.slowTestThreshold ? c.yellow : c.gray; + suffix += color(` ${Math.round(task.result.duration)}${c.dim("ms")}`); + } + if (this.ctx.config.logHeapUsage && task.result.heap != null) + suffix += c.magenta(` ${Math.floor(task.result.heap / 1024 / 1024)} MB heap used`); + logger.log(` ${getStateSymbol(task)} ${task.name} ${suffix}`); + for (const test of failed) { + logger.log(c.red(` ${pointer} ${getFullName(test)}`)); + (_d = (_c = test.result) == null ? void 0 : _c.errors) == null ? void 0 : _d.forEach((e) => { + logger.log(c.red(` ${F_RIGHT} ${e == null ? void 0 : e.message}`)); + }); + } + } + } + } + async onWatcherStart(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) { + this.resetLastRunLog(); + const failed = errors.length > 0 || hasFailed(files); + const failedSnap = hasFailedSnapshot(files); + if (failed) + this.ctx.logger.log(WAIT_FOR_CHANGE_FAIL); + else + this.ctx.logger.log(WAIT_FOR_CHANGE_PASS); + const hints = []; + if (this.mode !== "typecheck") + hints.push(HELP_HINT); + if (failedSnap) + hints.unshift(HELP_UPDATE_SNAP); + else + hints.push(HELP_QUITE); + this.ctx.logger.log(BADGE_PADDING + hints.join(c.dim(", "))); + if (this._lastRunCount) { + const LAST_RUN_TEXT = `rerun x${this._lastRunCount}`; + const LAST_RUN_TEXTS = [ + c.blue(LAST_RUN_TEXT), + c.gray(LAST_RUN_TEXT), + c.dim(c.gray(LAST_RUN_TEXT)) + ]; + this.ctx.logger.logUpdate(BADGE_PADDING + LAST_RUN_TEXTS[0]); + this._lastRunTimeout = 0; + this._lastRunTimer = safeSetInterval( + () => { + this._lastRunTimeout += 1; + if (this._lastRunTimeout >= LAST_RUN_TEXTS.length) + this.resetLastRunLog(); + else + this.ctx.logger.logUpdate(BADGE_PADDING + LAST_RUN_TEXTS[this._lastRunTimeout]); + }, + LAST_RUN_LOG_TIMEOUT / LAST_RUN_TEXTS.length + ); + } + } + resetLastRunLog() { + safeClearInterval(this._lastRunTimer); + this._lastRunTimer = void 0; + this.ctx.logger.logUpdate.clear(); + } + async onWatcherRerun(files, trigger) { + this.resetLastRunLog(); + this.watchFilters = files; + files.forEach((filepath) => { + let reruns = this._filesInWatchMode.get(filepath) ?? 0; + this._filesInWatchMode.set(filepath, ++reruns); + }); + const BADGE = c.inverse(c.bold(c.blue(" RERUN "))); + const TRIGGER = trigger ? c.dim(` ${this.relative(trigger)}`) : ""; + if (files.length > 1) { + this.ctx.logger.clearFullScreen(` +${BADGE}${TRIGGER} +`); + this._lastRunCount = 0; + } else if (files.length === 1) { + const rerun = this._filesInWatchMode.get(files[0]) ?? 1; + this._lastRunCount = rerun; + this.ctx.logger.clearFullScreen(` +${BADGE}${TRIGGER} ${c.blue(`x${rerun}`)} +`); + } + this._timeStart = new Date(); + this.start = performance.now(); + } + onUserConsoleLog(log) { + if (!this.shouldLog(log)) + return; + const task = log.taskId ? this.ctx.state.idMap.get(log.taskId) : void 0; + this.ctx.logger.log(c.gray(log.type + c.dim(` | ${task ? getFullName(task) : "unknown test"}`))); + process[log.type].write(`${log.content} +`); + } + shouldLog(log) { + var _a2, _b; + if (this.ctx.config.silent) + return false; + const shouldLog = (_b = (_a2 = this.ctx.config).onConsoleLog) == null ? void 0 : _b.call(_a2, log.content, log.type); + if (shouldLog === false) + return shouldLog; + return true; + } + onServerRestart(reason) { + this.ctx.logger.log(c.bold(c.magenta( + reason === "config" ? "\nRestarting due to config changes..." : "\nRestarting Vitest..." + ))); + } + async reportSummary(files) { + await this.printErrorsSummary(files); + if (this.mode === "benchmark") + await this.reportBenchmarkSummary(files); + else + await this.reportTestSummary(files); + } + async reportTestSummary(files) { + const tests = getTests(files); + const logger = this.ctx.logger; + const executionTime = this.end - this.start; + const collectTime = files.reduce((acc, test) => acc + Math.max(0, test.collectDuration || 0), 0); + const setupTime = files.reduce((acc, test) => acc + Math.max(0, test.setupDuration || 0), 0); + const testsTime = files.reduce((acc, test) => { + var _a2; + return acc + Math.max(0, ((_a2 = test.result) == null ? void 0 : _a2.duration) || 0); + }, 0); + const transformTime = Array.from(this.ctx.vitenode.fetchCache.values()).reduce((a, b) => a + ((b == null ? void 0 : b.duration) || 0), 0); + const threadTime = collectTime + testsTime + setupTime; + const padTitle = (str) => c.dim(`${str.padStart(11)} `); + const time = (time2) => { + if (time2 > 1e3) + return `${(time2 / 1e3).toFixed(2)}s`; + return `${Math.round(time2)}ms`; + }; + const snapshotOutput = renderSnapshotSummary(this.ctx.config.root, this.ctx.snapshot.summary); + if (snapshotOutput.length) { + logger.log(snapshotOutput.map( + (t, i) => i === 0 ? `${padTitle("Snapshots")} ${t}` : `${padTitle("")} ${t}` + ).join("\n")); + if (snapshotOutput.length > 1) + logger.log(); + } + logger.log(padTitle("Test Files"), getStateString(files)); + logger.log(padTitle("Tests"), getStateString(tests)); + if (this.mode === "typecheck") { + const failed = tests.filter((t) => { + var _a2, _b, _c; + return ((_a2 = t.meta) == null ? void 0 : _a2.typecheck) && ((_c = (_b = t.result) == null ? void 0 : _b.errors) == null ? void 0 : _c.length); + }); + logger.log(padTitle("Type Errors"), failed.length ? c.bold(c.red(`${failed} failed`)) : c.dim("no errors")); + } + logger.log(padTitle("Start at"), formatTimeString(this._timeStart)); + if (this.watchFilters) + logger.log(padTitle("Duration"), time(threadTime)); + else if (this.mode === "typecheck") + logger.log(padTitle("Duration"), time(executionTime)); + else + logger.log(padTitle("Duration"), time(executionTime) + c.dim(` (transform ${time(transformTime)}, setup ${time(setupTime)}, collect ${time(collectTime)}, tests ${time(testsTime)})`)); + logger.log(); + } + async printErrorsSummary(files) { + const logger = this.ctx.logger; + const suites = getSuites(files); + const tests = getTests(files); + const failedSuites = suites.filter((i) => { + var _a2; + return (_a2 = i.result) == null ? void 0 : _a2.errors; + }); + const failedTests = tests.filter((i) => { + var _a2; + return ((_a2 = i.result) == null ? void 0 : _a2.state) === "fail"; + }); + const failedTotal = countTestErrors(failedSuites) + countTestErrors(failedTests); + let current = 1; + const errorDivider = () => logger.error(`${c.red(c.dim(divider(`[${current++}/${failedTotal}]`, void 0, 1)))} +`); + if (failedSuites.length) { + logger.error(c.red(divider(c.bold(c.inverse(` Failed Suites ${failedSuites.length} `))))); + logger.error(); + await this.printTaskErrors(failedSuites, errorDivider); + } + if (failedTests.length) { + logger.error(c.red(divider(c.bold(c.inverse(` Failed Tests ${failedTests.length} `))))); + logger.error(); + await this.printTaskErrors(failedTests, errorDivider); + } + return tests; + } + async reportBenchmarkSummary(files) { + const logger = this.ctx.logger; + const benchs = getTests(files); + const topBenchs = benchs.filter((i) => { + var _a2, _b; + return ((_b = (_a2 = i.result) == null ? void 0 : _a2.benchmark) == null ? void 0 : _b.rank) === 1; + }); + logger.log(` +${c.cyan(c.inverse(c.bold(" BENCH ")))} ${c.cyan("Summary")} +`); + for (const bench of topBenchs) { + const group = bench.suite; + if (!group) + continue; + const groupName = getFullName(group); + logger.log(` ${bench.name}${c.dim(` - ${groupName}`)}`); + const siblings = group.tasks.filter((i) => { + var _a2; + return ((_a2 = i.result) == null ? void 0 : _a2.benchmark) && i !== bench; + }).sort((a, b) => a.result.benchmark.rank - b.result.benchmark.rank); + for (const sibling of siblings) { + const number = `${(sibling.result.benchmark.mean / bench.result.benchmark.mean).toFixed(2)}x`; + logger.log(` ${c.green(number)} ${c.gray("faster than")} ${sibling.name}`); + } + logger.log(""); + } + } + async printTaskErrors(tasks, errorDivider) { + var _a2, _b, _c; + const errorsQueue = []; + for (const task of tasks) { + (_b = (_a2 = task.result) == null ? void 0 : _a2.errors) == null ? void 0 : _b.forEach((error) => { + const errorItem = (error == null ? void 0 : error.stackStr) && errorsQueue.find((i) => { + var _a3; + return ((_a3 = i[0]) == null ? void 0 : _a3.stackStr) === error.stackStr; + }); + if (errorItem) + errorItem[1].push(task); + else + errorsQueue.push([error, [task]]); + }); + } + for (const [error, tasks2] of errorsQueue) { + for (const task of tasks2) { + const filepath = (task == null ? void 0 : task.filepath) || ""; + const projectName = (task == null ? void 0 : task.projectName) || ((_c = task.file) == null ? void 0 : _c.projectName); + let name = getFullName(task); + if (filepath) + name = `${name} ${c.dim(`[ ${this.relative(filepath)} ]`)}`; + this.ctx.logger.error(`${c.red(c.bold(c.inverse(" FAIL ")))} ${formatProjectName(projectName)}${name}`); + } + await this.ctx.logger.printError(error); + errorDivider(); + await Promise.resolve(); + } + } + registerUnhandledRejection() { + process.on("unhandledRejection", async (err) => { + process.exitCode = 1; + await this.ctx.logger.printError(err, true, "Unhandled Rejection"); + this.ctx.logger.error("\n\n"); + process.exit(1); + }); + } +} + +const DURATION_LONG$1 = 300; +const outputMap$1 = /* @__PURE__ */ new WeakMap(); +function formatFilepath$1(path) { + const lastSlash = Math.max(path.lastIndexOf("/") + 1, 0); + const basename = path.slice(lastSlash); + let firstDot = basename.indexOf("."); + if (firstDot < 0) + firstDot = basename.length; + firstDot += lastSlash; + return c.dim(path.slice(0, lastSlash)) + path.slice(lastSlash, firstDot) + c.dim(path.slice(firstDot)); +} +function formatNumber$1(number) { + const res = String(number.toFixed(number < 100 ? 4 : 2)).split("."); + return res[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ",") + (res[1] ? `.${res[1]}` : ""); +} +function renderHookState(task, hookName, level = 0) { + var _a, _b; + const state = (_b = (_a = task.result) == null ? void 0 : _a.hooks) == null ? void 0 : _b[hookName]; + if (state && state === "run") + return `${" ".repeat(level)} ${getHookStateSymbol(task, hookName)} ${c.dim(`[ ${hookName} ]`)}`; + return ""; +} +function renderBenchmarkItems$1(result) { + return [ + result.name, + formatNumber$1(result.hz || 0), + formatNumber$1(result.p99 || 0), + `\xB1${result.rme.toFixed(2)}%`, + result.samples.length.toString() + ]; +} +function renderBenchmark$1(task, tasks) { + var _a; + const result = (_a = task.result) == null ? void 0 : _a.benchmark; + if (!result) + return task.name; + const benchs = tasks.map((i) => { + var _a2; + return i.type === "benchmark" ? (_a2 = i.result) == null ? void 0 : _a2.benchmark : void 0; + }).filter(notNullish); + const allItems = benchs.map(renderBenchmarkItems$1); + const items = renderBenchmarkItems$1(result); + const padded = items.map((i, idx) => { + const width = Math.max(...allItems.map((i2) => i2[idx].length)); + return idx ? i.padStart(width, " ") : i.padEnd(width, " "); + }); + return [ + padded[0], + c.dim(" "), + c.blue(padded[1]), + c.dim(" ops/sec "), + c.cyan(padded[3]), + c.dim(` (${padded[4]} samples)`), + result.rank === 1 ? c.bold(c.green(" fastest")) : result.rank === benchs.length && benchs.length > 2 ? c.bold(c.gray(" slowest")) : "" + ].join(""); +} +function renderTree$1(tasks, options, level = 0) { + var _a, _b, _c, _d, _e, _f, _g; + let output = []; + for (const task of tasks) { + let suffix = ""; + let prefix = ` ${getStateSymbol(task)} `; + if (level === 0 && task.type === "suite" && task.projectName) + prefix += formatProjectName(task.projectName); + if (task.type === "test" && ((_a = task.result) == null ? void 0 : _a.retryCount) && task.result.retryCount > 1) + suffix += c.yellow(` (retry x${task.result.retryCount})`); + if (task.type === "suite" && !((_b = task.meta) == null ? void 0 : _b.typecheck)) { + const tests = getTests(task); + suffix += c.dim(` (${tests.length})`); + } + if (task.mode === "skip" || task.mode === "todo") + suffix += ` ${c.dim(c.gray("[skipped]"))}`; + if (((_c = task.result) == null ? void 0 : _c.duration) != null) { + if (task.result.duration > DURATION_LONG$1) + suffix += c.yellow(` ${Math.round(task.result.duration)}${c.dim("ms")}`); + } + if (options.showHeap && ((_d = task.result) == null ? void 0 : _d.heap) != null) + suffix += c.magenta(` ${Math.floor(task.result.heap / 1024 / 1024)} MB heap used`); + let name = task.name; + if (level === 0) + name = formatFilepath$1(name); + const padding = " ".repeat(level); + const body = task.type === "benchmark" ? renderBenchmark$1(task, tasks) : name; + output.push(padding + prefix + body + suffix); + if (((_e = task.result) == null ? void 0 : _e.state) !== "pass" && outputMap$1.get(task) != null) { + let data = outputMap$1.get(task); + if (typeof data === "string") { + data = stripAnsi(data.trim().split("\n").filter(Boolean).pop()); + if (data === "") + data = void 0; + } + if (data != null) { + const out = `${" ".repeat(level)}${F_RIGHT} ${data}`; + output.push(` ${c.gray(cliTruncate(out, getCols(-3)))}`); + } + } + output = output.concat(renderHookState(task, "beforeAll", level + 1)); + output = output.concat(renderHookState(task, "beforeEach", level + 1)); + if (task.type === "suite" && task.tasks.length > 0) { + if (((_f = task.result) == null ? void 0 : _f.state) === "fail" || ((_g = task.result) == null ? void 0 : _g.state) === "run" || options.renderSucceed) + output = output.concat(renderTree$1(task.tasks, options, level + 1)); + } + output = output.concat(renderHookState(task, "afterAll", level + 1)); + output = output.concat(renderHookState(task, "afterEach", level + 1)); + } + return output.filter(Boolean).join("\n"); +} +const createListRenderer = (_tasks, options) => { + let tasks = _tasks; + let timer; + const log = options.logger.logUpdate; + function update() { + log(renderTree$1(tasks, options)); + } + return { + start() { + if (timer) + return this; + timer = safeSetInterval(update, 200); + return this; + }, + update(_tasks2) { + tasks = _tasks2; + update(); + return this; + }, + async stop() { + if (timer) { + safeClearInterval(timer); + timer = void 0; + } + log.clear(); + options.logger.log(renderTree$1(tasks, options)); + return this; + }, + clear() { + log.clear(); + } + }; +}; + +class DefaultReporter extends BaseReporter { + constructor() { + super(...arguments); + this.rendererOptions = {}; + } + async onTestRemoved(trigger) { + await this.stopListRender(); + this.ctx.logger.clearScreen(c.yellow("Test removed...") + (trigger ? c.dim(` [ ${this.relative(trigger)} ] +`) : ""), true); + const files = this.ctx.state.getFiles(this.watchFilters); + createListRenderer(files, this.rendererOptions).stop(); + this.ctx.logger.log(); + await super.reportSummary(files); + super.onWatcherStart(); + } + onCollected() { + if (this.isTTY) { + this.rendererOptions.logger = this.ctx.logger; + this.rendererOptions.showHeap = this.ctx.config.logHeapUsage; + this.rendererOptions.mode = this.mode; + const files = this.ctx.state.getFiles(this.watchFilters); + if (!this.renderer) + this.renderer = createListRenderer(files, this.rendererOptions).start(); + else + this.renderer.update(files); + } + } + async onFinished(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) { + await this.stopListRender(); + this.ctx.logger.log(); + await super.onFinished(files, errors); + } + async onWatcherStart(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) { + await this.stopListRender(); + await super.onWatcherStart(files, errors); + } + async stopListRender() { + var _a; + await ((_a = this.renderer) == null ? void 0 : _a.stop()); + this.renderer = void 0; + } + async onWatcherRerun(files, trigger) { + await this.stopListRender(); + await super.onWatcherRerun(files, trigger); + } + onUserConsoleLog(log) { + var _a; + if (!this.shouldLog(log)) + return; + (_a = this.renderer) == null ? void 0 : _a.clear(); + super.onUserConsoleLog(log); + } +} + +const check = c.green("\xB7"); +const cross = c.red("x"); +const pending = c.yellow("*"); +const skip = c.dim(c.gray("-")); +function render(tasks) { + const all = getTests(tasks); + return all.map((i) => { + var _a; + if (i.mode === "skip" || i.mode === "todo") + return skip; + switch ((_a = i.result) == null ? void 0 : _a.state) { + case "pass": + return check; + case "fail": + return cross; + default: + return pending; + } + }).join(""); +} +const createDotRenderer = (_tasks, options) => { + let tasks = _tasks; + let timer; + const log = options.logger.logUpdate; + function update() { + log(render(tasks)); + } + return { + start() { + if (timer) + return this; + timer = safeSetInterval(update, 200); + return this; + }, + update(_tasks2) { + tasks = _tasks2; + update(); + return this; + }, + async stop() { + if (timer) { + safeClearInterval(timer); + timer = void 0; + } + log.clear(); + options.logger.log(render(tasks)); + return this; + }, + clear() { + log.clear(); + } + }; +}; + +class DotReporter extends BaseReporter { + onCollected() { + if (this.isTTY) { + const files = this.ctx.state.getFiles(this.watchFilters); + if (!this.renderer) + this.renderer = createDotRenderer(files, { logger: this.ctx.logger }).start(); + else + this.renderer.update(files); + } + } + async onFinished(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) { + await this.stopListRender(); + this.ctx.logger.log(); + await super.onFinished(files, errors); + } + async onWatcherStart() { + await this.stopListRender(); + super.onWatcherStart(); + } + async stopListRender() { + var _a; + (_a = this.renderer) == null ? void 0 : _a.stop(); + this.renderer = void 0; + await new Promise((resolve) => safeSetTimeout(resolve, 10)); + } + async onWatcherRerun(files, trigger) { + await this.stopListRender(); + await super.onWatcherRerun(files, trigger); + } + onUserConsoleLog(log) { + var _a; + (_a = this.renderer) == null ? void 0 : _a.clear(); + super.onUserConsoleLog(log); + } +} + +const getOutputFile = (config, reporter) => { + if (!(config == null ? void 0 : config.outputFile)) + return; + if (typeof config.outputFile === "string") + return config.outputFile; + return config.outputFile[reporter]; +}; + +const StatusMap = { + fail: "failed", + only: "pending", + pass: "passed", + run: "pending", + skip: "skipped", + todo: "todo" +}; +class JsonReporter$1 { + constructor() { + this.start = 0; + } + onInit(ctx) { + this.ctx = ctx; + this.start = Date.now(); + } + async logTasks(files) { + var _a, _b, _c; + const suites = getSuites(files); + const numTotalTestSuites = suites.length; + const tests = getTests(files); + const numTotalTests = tests.length; + const numFailedTestSuites = suites.filter((s) => { + var _a2; + return (_a2 = s.result) == null ? void 0 : _a2.errors; + }).length; + const numPassedTestSuites = numTotalTestSuites - numFailedTestSuites; + const numPendingTestSuites = suites.filter((s) => { + var _a2; + return ((_a2 = s.result) == null ? void 0 : _a2.state) === "run"; + }).length; + const numFailedTests = tests.filter((t) => { + var _a2; + return ((_a2 = t.result) == null ? void 0 : _a2.state) === "fail"; + }).length; + const numPassedTests = numTotalTests - numFailedTests; + const numPendingTests = tests.filter((t) => { + var _a2; + return ((_a2 = t.result) == null ? void 0 : _a2.state) === "run"; + }).length; + const numTodoTests = tests.filter((t) => t.mode === "todo").length; + const testResults = []; + const success = numFailedTestSuites === 0 && numFailedTests === 0; + for (const file of files) { + const tests2 = getTests([file]); + let startTime = tests2.reduce((prev, next) => { + var _a2; + return Math.min(prev, ((_a2 = next.result) == null ? void 0 : _a2.startTime) ?? Infinity); + }, Infinity); + if (startTime === Infinity) + startTime = this.start; + const endTime = tests2.reduce((prev, next) => { + var _a2, _b2; + return Math.max(prev, (((_a2 = next.result) == null ? void 0 : _a2.startTime) ?? 0) + (((_b2 = next.result) == null ? void 0 : _b2.duration) ?? 0)); + }, startTime); + const assertionResults = await Promise.all(tests2.map(async (t) => { + var _a2, _b2, _c2, _d; + const ancestorTitles = []; + let iter = t.suite; + while (iter) { + ancestorTitles.push(iter.name); + iter = iter.suite; + } + ancestorTitles.reverse(); + return { + ancestorTitles, + fullName: ancestorTitles.length > 0 ? `${ancestorTitles.join(" ")} ${t.name}` : t.name, + status: StatusMap[((_a2 = t.result) == null ? void 0 : _a2.state) || t.mode] || "skipped", + title: t.name, + duration: (_b2 = t.result) == null ? void 0 : _b2.duration, + failureMessages: ((_d = (_c2 = t.result) == null ? void 0 : _c2.errors) == null ? void 0 : _d.map((e) => e.message)) || [], + location: await this.getFailureLocation(t) + }; + })); + if (tests2.some((t) => { + var _a2; + return ((_a2 = t.result) == null ? void 0 : _a2.state) === "run"; + })) { + this.ctx.logger.warn("WARNING: Some tests are still running when generating the JSON report.This is likely an internal bug in Vitest.Please report it to https://github.com/vitest-dev/vitest/issues"); + } + testResults.push({ + assertionResults, + startTime, + endTime, + status: tests2.some((t) => { + var _a2; + return ((_a2 = t.result) == null ? void 0 : _a2.state) === "fail"; + }) ? "failed" : "passed", + message: ((_c = (_b = (_a = file.result) == null ? void 0 : _a.errors) == null ? void 0 : _b[0]) == null ? void 0 : _c.message) ?? "", + name: file.filepath + }); + } + const result = { + numTotalTestSuites, + numPassedTestSuites, + numFailedTestSuites, + numPendingTestSuites, + numTotalTests, + numPassedTests, + numFailedTests, + numPendingTests, + numTodoTests, + startTime: this.start, + success, + testResults + }; + await this.writeReport(JSON.stringify(result, null, 2)); + } + async onFinished(files = this.ctx.state.getFiles()) { + await this.logTasks(files); + } + async writeReport(report) { + const outputFile = getOutputFile(this.ctx.config, "json"); + if (outputFile) { + const reportFile = resolve(this.ctx.config.root, outputFile); + const outputDirectory = dirname(reportFile); + if (!existsSync(outputDirectory)) + await promises.mkdir(outputDirectory, { recursive: true }); + await promises.writeFile(reportFile, report, "utf-8"); + this.ctx.logger.log(`JSON report written to ${reportFile}`); + } else { + this.ctx.logger.log(report); + } + } + async getFailureLocation(test) { + var _a, _b; + const error = (_b = (_a = test.result) == null ? void 0 : _a.errors) == null ? void 0 : _b[0]; + if (!error) + return; + const stack = parseStacktrace(error); + const frame = stack[stack.length - 1]; + if (!frame) + return; + return { line: frame.line, column: frame.column }; + } +} + +class VerboseReporter extends DefaultReporter { + constructor() { + super(); + this.rendererOptions.renderSucceed = true; + } + onTaskUpdate(packs) { + var _a, _b, _c; + if (this.isTTY) + return; + for (const pack of packs) { + const task = this.ctx.state.idMap.get(pack[0]); + if (task && task.type === "test" && ((_a = task.result) == null ? void 0 : _a.state) && ((_b = task.result) == null ? void 0 : _b.state) !== "run") { + let title = ` ${getStateSymbol(task)} ${getFullName(task)}`; + if (this.ctx.config.logHeapUsage && task.result.heap != null) + title += c.magenta(` ${Math.floor(task.result.heap / 1024 / 1024)} MB heap used`); + this.ctx.logger.log(title); + if (task.result.state === "fail") { + (_c = task.result.errors) == null ? void 0 : _c.forEach((error) => { + this.ctx.logger.log(c.red(` ${F_RIGHT} ${error == null ? void 0 : error.message}`)); + }); + } + } + } + } +} + +class IndentedLogger { + constructor(baseLog) { + this.baseLog = baseLog; + this.currentIndent = ""; + } + indent() { + this.currentIndent += " "; + } + unindent() { + this.currentIndent = this.currentIndent.substring(0, this.currentIndent.length - 4); + } + log(text) { + return this.baseLog(this.currentIndent + text); + } +} + +function yamlString(str) { + return `"${str.replace(/"/g, '\\"')}"`; +} +function tapString(str) { + return str.replace(/\\/g, "\\\\").replace(/#/g, "\\#").replace(/\n/g, " "); +} +class TapReporter { + onInit(ctx) { + this.ctx = ctx; + this.logger = new IndentedLogger(ctx.logger.log.bind(ctx.logger)); + } + static getComment(task) { + var _a; + if (task.mode === "skip") + return " # SKIP"; + else if (task.mode === "todo") + return " # TODO"; + else if (((_a = task.result) == null ? void 0 : _a.duration) != null) + return ` # time=${task.result.duration.toFixed(2)}ms`; + else + return ""; + } + logErrorDetails(error, stack) { + this.logger.log(`name: ${yamlString(error.name)}`); + this.logger.log(`message: ${yamlString(error.message)}`); + if (stack) { + this.logger.log(`stack: ${yamlString(`${stack.file}:${stack.line}:${stack.column}`)}`); + } + } + logTasks(tasks) { + var _a, _b; + this.logger.log(`1..${tasks.length}`); + for (const [i, task] of tasks.entries()) { + const id = i + 1; + const ok = ((_a = task.result) == null ? void 0 : _a.state) === "pass" || task.mode === "skip" || task.mode === "todo" ? "ok" : "not ok"; + const comment = TapReporter.getComment(task); + if (task.type === "suite" && task.tasks.length > 0) { + this.logger.log(`${ok} ${id} - ${tapString(task.name)}${comment} {`); + this.logger.indent(); + this.logTasks(task.tasks); + this.logger.unindent(); + this.logger.log("}"); + } else { + this.logger.log(`${ok} ${id} - ${tapString(task.name)}${comment}`); + if (((_b = task.result) == null ? void 0 : _b.state) === "fail" && task.result.errors) { + this.logger.indent(); + task.result.errors.forEach((error) => { + const stacks = parseStacktrace(error); + const stack = stacks[0]; + this.logger.log("---"); + this.logger.log("error:"); + this.logger.indent(); + this.logErrorDetails(error); + this.logger.unindent(); + if (stack) + this.logger.log(`at: ${yamlString(`${stack.file}:${stack.line}:${stack.column}`)}`); + if (error.showDiff) { + this.logger.log(`actual: ${yamlString(error.actual)}`); + this.logger.log(`expected: ${yamlString(error.expected)}`); + } + }); + this.logger.log("..."); + this.logger.unindent(); + } + } + } + } + async onFinished(files = this.ctx.state.getFiles()) { + this.logger.log("TAP version 13"); + this.logTasks(files); + } +} + +function flattenTasks$1(task, baseName = "") { + const base = baseName ? `${baseName} > ` : ""; + if (task.type === "suite") { + return task.tasks.flatMap((child) => flattenTasks$1(child, `${base}${task.name}`)); + } else { + return [{ + ...task, + name: `${base}${task.name}` + }]; + } +} +function removeInvalidXMLCharacters(value, removeDiscouragedChars) { + let regex = /((?:[\0-\x08\x0B\f\x0E-\x1F\uFFFD\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/g; + value = String(value || "").replace(regex, ""); + if (removeDiscouragedChars) { + regex = new RegExp( + "([\\x7F-\\x84]|[\\x86-\\x9F]|[\\uFDD0-\\uFDEF]|(?:\\uD83F[\\uDFFE\\uDFFF])|(?:\\uD87F[\\uDFFE\\uDFFF])|(?:\\uD8BF[\\uDFFE\\uDFFF])|(?:\\uD8FF[\\uDFFE\\uDFFF])|(?:\\uD93F[\\uDFFE\\uDFFF])|(?:\\uD97F[\\uDFFE\\uDFFF])|(?:\\uD9BF[\\uDFFE\\uDFFF])|(?:\\uD9FF[\\uDFFE\\uDFFF])|(?:\\uDA3F[\\uDFFE\\uDFFF])|(?:\\uDA7F[\\uDFFE\\uDFFF])|(?:\\uDABF[\\uDFFE\\uDFFF])|(?:\\uDAFF[\\uDFFE\\uDFFF])|(?:\\uDB3F[\\uDFFE\\uDFFF])|(?:\\uDB7F[\\uDFFE\\uDFFF])|(?:\\uDBBF[\\uDFFE\\uDFFF])|(?:\\uDBFF[\\uDFFE\\uDFFF])(?:[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]))", + "g" + ); + value = value.replace(regex, ""); + } + return value; +} +function escapeXML(value) { + return removeInvalidXMLCharacters( + String(value).replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">"), + true + ); +} +function executionTime(durationMS) { + return (durationMS / 1e3).toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: 10 }); +} +function getDuration(task) { + var _a; + const duration = ((_a = task.result) == null ? void 0 : _a.duration) ?? 0; + return executionTime(duration); +} +class JUnitReporter { + constructor() { + this._timeStart = new Date(); + } + async onInit(ctx) { + this.ctx = ctx; + const outputFile = getOutputFile(this.ctx.config, "junit"); + if (outputFile) { + this.reportFile = resolve(this.ctx.config.root, outputFile); + const outputDirectory = dirname(this.reportFile); + if (!existsSync(outputDirectory)) + await promises.mkdir(outputDirectory, { recursive: true }); + const fileFd = await promises.open(this.reportFile, "w+"); + this.baseLog = async (text) => await promises.writeFile(fileFd, `${text} +`); + } else { + this.baseLog = async (text) => this.ctx.logger.log(text); + } + this._timeStart = new Date(); + this.logger = new IndentedLogger(this.baseLog); + } + async writeElement(name, attrs, children) { + const pairs = []; + for (const key in attrs) { + const attr = attrs[key]; + if (attr === void 0) + continue; + pairs.push(`${key}="${escapeXML(attr)}"`); + } + await this.logger.log(`<${name}${pairs.length ? ` ${pairs.join(" ")}` : ""}>`); + this.logger.indent(); + await children.call(this); + this.logger.unindent(); + await this.logger.log(``); + } + async writeErrorDetails(error) { + const errorName = error.name ?? error.nameStr ?? "Unknown Error"; + const errorDetails = `${errorName}: ${error.message}`; + await this.baseLog(escapeXML(errorDetails)); + const stack = parseStacktrace(error); + for (const frame of stack) { + const path = relative(this.ctx.config.root, frame.file); + await this.baseLog(` ${F_POINTER} ${[frame.method, `${path}:${frame.line}:${frame.column}`].filter(Boolean).join(" ")}`); + if (frame.file in this.ctx.state.filesMap) + break; + } + } + async writeLogs(task, type) { + if (task.logs == null || task.logs.length === 0) + return; + const logType = type === "err" ? "stderr" : "stdout"; + const logs = task.logs.filter((log) => log.type === logType); + if (logs.length === 0) + return; + await this.writeElement(`system-${type}`, {}, async () => { + for (const log of logs) + await this.baseLog(escapeXML(log.content)); + }); + } + async writeTasks(tasks, filename) { + for (const task of tasks) { + await this.writeElement("testcase", { + classname: filename, + name: task.name, + time: getDuration(task) + }, async () => { + var _a, _b; + await this.writeLogs(task, "out"); + await this.writeLogs(task, "err"); + if (task.mode === "skip" || task.mode === "todo") + await this.logger.log(""); + if (((_a = task.result) == null ? void 0 : _a.state) === "fail") { + const promises = ((_b = task.result.errors) == null ? void 0 : _b.map(async (error) => { + await this.writeElement("failure", { + message: error == null ? void 0 : error.message, + type: (error == null ? void 0 : error.name) ?? (error == null ? void 0 : error.nameStr) + }, async () => { + if (!error) + return; + await this.writeErrorDetails(error); + }); + })) || []; + await Promise.all(promises); + } + }); + } + } + async onFinished(files = this.ctx.state.getFiles()) { + await this.logger.log(''); + const transformed = files.map((file) => { + const tasks = file.tasks.flatMap((task) => flattenTasks$1(task)); + const stats2 = tasks.reduce( + (stats3, task) => { + var _a, _b; + return { + passed: stats3.passed + Number(((_a = task.result) == null ? void 0 : _a.state) === "pass"), + failures: stats3.failures + Number(((_b = task.result) == null ? void 0 : _b.state) === "fail"), + skipped: stats3.skipped + Number(task.mode === "skip" || task.mode === "todo") + }; + }, + { + passed: 0, + failures: 0, + skipped: 0 + } + ); + return { + ...file, + tasks, + stats: stats2 + }; + }); + const stats = transformed.reduce((stats2, file) => { + stats2.tests += file.tasks.length; + stats2.failures += file.stats.failures; + return stats2; + }, { + name: process.env.VITEST_JUNIT_SUITE_NAME || "vitest tests", + tests: 0, + failures: 0, + errors: 0, + time: executionTime(new Date().getTime() - this._timeStart.getTime()) + }); + await this.writeElement("testsuites", stats, async () => { + for (const file of transformed) { + await this.writeElement("testsuite", { + name: file.name, + timestamp: new Date().toISOString(), + hostname: hostname(), + tests: file.tasks.length, + failures: file.stats.failures, + errors: 0, + skipped: file.stats.skipped, + time: getDuration(file) + }, async () => { + await this.writeTasks(file.tasks, file.name); + }); + } + }); + if (this.reportFile) + this.ctx.logger.log(`JUNIT report written to ${this.reportFile}`); + } +} + +function flattenTasks(task, baseName = "") { + const base = baseName ? `${baseName} > ` : ""; + if (task.type === "suite" && task.tasks.length > 0) { + return task.tasks.flatMap((child) => flattenTasks(child, `${base}${task.name}`)); + } else { + return [{ + ...task, + name: `${base}${task.name}` + }]; + } +} +class TapFlatReporter extends TapReporter { + onInit(ctx) { + super.onInit(ctx); + } + async onFinished(files = this.ctx.state.getFiles()) { + this.ctx.logger.log("TAP version 13"); + const flatTasks = files.flatMap((task) => flattenTasks(task)); + this.logTasks(flatTasks); + } +} + +class JsonReporter { + constructor() { + this.start = 0; + } + onInit(ctx) { + this.ctx = ctx; + } + async logTasks(files) { + var _a; + const suites = getSuites(files); + const numTotalTestSuites = suites.length; + const tests = getTests(files); + const numTotalTests = tests.length; + const testResults = {}; + const outputFile = getOutputFile(this.ctx.config.benchmark, "json"); + for (const file of files) { + const tests2 = getTests([file]); + for (const test of tests2) { + const res = (_a = test.result) == null ? void 0 : _a.benchmark; + if (!res || test.mode === "skip") + continue; + if (!outputFile) + res.samples = "ignore on terminal"; + testResults[test.suite.name] = (testResults[test.suite.name] || []).concat(res); + } + if (tests2.some((t) => { + var _a2; + return ((_a2 = t.result) == null ? void 0 : _a2.state) === "run"; + })) { + this.ctx.logger.warn("WARNING: Some tests are still running when generating the json report.This is likely an internal bug in Vitest.Please report it to https://github.com/vitest-dev/vitest/issues"); + } + } + const result = { + numTotalTestSuites, + numTotalTests, + testResults + }; + await this.writeReport(JSON.stringify(result, null, 2)); + } + async onFinished(files = this.ctx.state.getFiles()) { + await this.logTasks(files); + } + async writeReport(report) { + const outputFile = getOutputFile(this.ctx.config.benchmark, "json"); + if (outputFile) { + const reportFile = resolve(this.ctx.config.root, outputFile); + const outputDirectory = dirname(reportFile); + if (!existsSync(outputDirectory)) + await promises.mkdir(outputDirectory, { recursive: true }); + await promises.writeFile(reportFile, report, "utf-8"); + this.ctx.logger.log(`json report written to ${reportFile}`); + } else { + this.ctx.logger.log(report); + } + } +} + +const DURATION_LONG = 300; +const outputMap = /* @__PURE__ */ new WeakMap(); +function formatFilepath(path) { + const lastSlash = Math.max(path.lastIndexOf("/") + 1, 0); + const basename = path.slice(lastSlash); + let firstDot = basename.indexOf("."); + if (firstDot < 0) + firstDot = basename.length; + firstDot += lastSlash; + return c.dim(path.slice(0, lastSlash)) + path.slice(lastSlash, firstDot) + c.dim(path.slice(firstDot)); +} +function formatNumber(number) { + const res = String(number.toFixed(number < 100 ? 4 : 2)).split("."); + return res[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ",") + (res[1] ? `.${res[1]}` : ""); +} +const tableHead = ["name", "hz", "min", "max", "mean", "p75", "p99", "p995", "p999", "rme", "samples"]; +function renderTableHead(tasks) { + const benchs = tasks.map((i) => { + var _a; + return i.type === "benchmark" ? (_a = i.result) == null ? void 0 : _a.benchmark : void 0; + }).filter(notNullish); + const allItems = benchs.map(renderBenchmarkItems).concat([tableHead]); + return `${" ".repeat(3)}${tableHead.map((i, idx) => { + const width = Math.max(...allItems.map((i2) => i2[idx].length)); + return idx ? i.padStart(width, " ") : i.padEnd(width, " "); + }).map(c.bold).join(" ")}`; +} +function renderBenchmarkItems(result) { + return [ + result.name, + formatNumber(result.hz || 0), + formatNumber(result.min || 0), + formatNumber(result.max || 0), + formatNumber(result.mean || 0), + formatNumber(result.p75 || 0), + formatNumber(result.p99 || 0), + formatNumber(result.p995 || 0), + formatNumber(result.p999 || 0), + `\xB1${(result.rme || 0).toFixed(2)}%`, + result.samples.length.toString() + ]; +} +function renderBenchmark(task, tasks) { + var _a; + const result = (_a = task.result) == null ? void 0 : _a.benchmark; + if (!result) + return task.name; + const benchs = tasks.map((i) => { + var _a2; + return i.type === "benchmark" ? (_a2 = i.result) == null ? void 0 : _a2.benchmark : void 0; + }).filter(notNullish); + const allItems = benchs.map(renderBenchmarkItems).concat([tableHead]); + const items = renderBenchmarkItems(result); + const padded = items.map((i, idx) => { + const width = Math.max(...allItems.map((i2) => i2[idx].length)); + return idx ? i.padStart(width, " ") : i.padEnd(width, " "); + }); + return [ + padded[0], + c.blue(padded[1]), + c.cyan(padded[2]), + c.cyan(padded[3]), + c.cyan(padded[4]), + c.cyan(padded[5]), + c.cyan(padded[6]), + c.cyan(padded[7]), + c.cyan(padded[8]), + c.dim(padded[9]), + c.dim(padded[10]), + result.rank === 1 ? c.bold(c.green(" fastest")) : result.rank === benchs.length && benchs.length > 2 ? c.bold(c.gray(" slowest")) : "" + ].join(" "); +} +function renderTree(tasks, options, level = 0) { + var _a, _b, _c, _d; + let output = []; + let idx = 0; + for (const task of tasks) { + const padding = " ".repeat(level ? 1 : 0); + let prefix = ""; + if (idx === 0 && task.type === "benchmark") + prefix += `${renderTableHead(tasks)} +${padding}`; + prefix += ` ${getStateSymbol(task)} `; + let suffix = ""; + if (task.type === "suite") + suffix += c.dim(` (${getTests(task).length})`); + if (task.mode === "skip" || task.mode === "todo") + suffix += ` ${c.dim(c.gray("[skipped]"))}`; + if (((_a = task.result) == null ? void 0 : _a.duration) != null) { + if (task.result.duration > DURATION_LONG) + suffix += c.yellow(` ${Math.round(task.result.duration)}${c.dim("ms")}`); + } + if (options.showHeap && ((_b = task.result) == null ? void 0 : _b.heap) != null) + suffix += c.magenta(` ${Math.floor(task.result.heap / 1024 / 1024)} MB heap used`); + let name = task.name; + if (level === 0) + name = formatFilepath(name); + const body = task.type === "benchmark" ? renderBenchmark(task, tasks) : name; + output.push(padding + prefix + body + suffix); + if (((_c = task.result) == null ? void 0 : _c.state) !== "pass" && outputMap.get(task) != null) { + let data = outputMap.get(task); + if (typeof data === "string") { + data = stripAnsi(data.trim().split("\n").filter(Boolean).pop()); + if (data === "") + data = void 0; + } + if (data != null) { + const out = `${" ".repeat(level)}${F_RIGHT} ${data}`; + output.push(` ${c.gray(cliTruncate(out, getCols(-3)))}`); + } + } + if (task.type === "suite" && task.tasks.length > 0) { + if ((_d = task.result) == null ? void 0 : _d.state) + output = output.concat(renderTree(task.tasks, options, level + 1)); + } + idx++; + } + return output.filter(Boolean).join("\n"); +} +const createTableRenderer = (_tasks, options) => { + let tasks = _tasks; + let timer; + const log = options.logger.logUpdate; + function update() { + log(renderTree(tasks, options)); + } + return { + start() { + if (timer) + return this; + timer = safeSetInterval(update, 200); + return this; + }, + update(_tasks2) { + tasks = _tasks2; + update(); + return this; + }, + async stop() { + if (timer) { + safeClearInterval(timer); + timer = void 0; + } + log.clear(); + options.logger.log(renderTree(tasks, options)); + return this; + }, + clear() { + log.clear(); + } + }; +}; + +class TableReporter extends BaseReporter { + constructor() { + super(...arguments); + this.rendererOptions = {}; + } + async onTestRemoved(trigger) { + await this.stopListRender(); + this.ctx.logger.clearScreen(c.yellow("Test removed...") + (trigger ? c.dim(` [ ${this.relative(trigger)} ] +`) : ""), true); + const files = this.ctx.state.getFiles(this.watchFilters); + createTableRenderer(files, this.rendererOptions).stop(); + this.ctx.logger.log(); + await super.reportSummary(files); + super.onWatcherStart(); + } + onCollected() { + if (this.isTTY) { + this.rendererOptions.logger = this.ctx.logger; + this.rendererOptions.showHeap = this.ctx.config.logHeapUsage; + const files = this.ctx.state.getFiles(this.watchFilters); + if (!this.renderer) + this.renderer = createTableRenderer(files, this.rendererOptions).start(); + else + this.renderer.update(files); + } + } + async onFinished(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) { + await this.stopListRender(); + this.ctx.logger.log(); + await super.onFinished(files, errors); + } + async onWatcherStart() { + await this.stopListRender(); + await super.onWatcherStart(); + } + async stopListRender() { + var _a; + await ((_a = this.renderer) == null ? void 0 : _a.stop()); + this.renderer = void 0; + } + async onWatcherRerun(files, trigger) { + await this.stopListRender(); + await super.onWatcherRerun(files, trigger); + } + onUserConsoleLog(log) { + var _a; + if (!this.shouldLog(log)) + return; + (_a = this.renderer) == null ? void 0 : _a.clear(); + super.onUserConsoleLog(log); + } +} + +const BenchmarkReportsMap = { + default: TableReporter, + verbose: VerboseReporter, + json: JsonReporter +}; + +const ReportersMap = { + "default": DefaultReporter, + "verbose": VerboseReporter, + "dot": DotReporter, + "json": JsonReporter$1, + "tap": TapReporter, + "tap-flat": TapFlatReporter, + "junit": JUnitReporter +}; + +async function loadCustomReporterModule(path, runner) { + let customReporterModule; + try { + customReporterModule = await runner.executeId(path); + } catch (customReporterModuleError) { + throw new Error(`Failed to load custom Reporter from ${path}`, { cause: customReporterModuleError }); + } + if (customReporterModule.default === null || customReporterModule.default === void 0) + throw new Error(`Custom reporter loaded from ${path} was not the default export`); + return customReporterModule.default; +} +function createReporters(reporterReferences, runner) { + const promisedReporters = reporterReferences.map(async (referenceOrInstance) => { + if (typeof referenceOrInstance === "string") { + if (referenceOrInstance === "html") { + await ensurePackageInstalled("@vitest/ui", runner.root); + const CustomReporter = await loadCustomReporterModule("@vitest/ui/reporter", runner); + return new CustomReporter(); + } else if (referenceOrInstance in ReportersMap) { + const BuiltinReporter = ReportersMap[referenceOrInstance]; + return new BuiltinReporter(); + } else { + const CustomReporter = await loadCustomReporterModule(referenceOrInstance, runner); + return new CustomReporter(); + } + } + return referenceOrInstance; + }); + return Promise.all(promisedReporters); +} +function createBenchmarkReporters(reporterReferences, runner) { + const promisedReporters = reporterReferences.map(async (referenceOrInstance) => { + if (typeof referenceOrInstance === "string") { + if (referenceOrInstance in BenchmarkReportsMap) { + const BuiltinReporter = BenchmarkReportsMap[referenceOrInstance]; + return new BuiltinReporter(); + } else { + const CustomReporter = await loadCustomReporterModule(referenceOrInstance, runner); + return new CustomReporter(); + } + } + return referenceOrInstance; + }); + return Promise.all(promisedReporters); +} + +const isAggregateError = (err) => { + if (typeof AggregateError !== "undefined" && err instanceof AggregateError) + return true; + return err instanceof Error && "errors" in err; +}; +class StateManager { + constructor() { + this.filesMap = /* @__PURE__ */ new Map(); + this.pathsSet = /* @__PURE__ */ new Set(); + this.collectingPromise = void 0; + this.idMap = /* @__PURE__ */ new Map(); + this.taskFileMap = /* @__PURE__ */ new WeakMap(); + this.errorsSet = /* @__PURE__ */ new Set(); + } + catchError(err, type) { + if (isAggregateError(err)) + return err.errors.forEach((error) => this.catchError(error, type)); + err.type = type; + this.errorsSet.add(err); + } + clearErrors() { + this.errorsSet.clear(); + } + getUnhandledErrors() { + return Array.from(this.errorsSet.values()); + } + startCollectingPaths() { + let _resolve; + const promise = new Promise((resolve) => { + _resolve = resolve; + }); + this.collectingPromise = { promise, resolve: _resolve }; + } + finishCollectingPaths() { + var _a; + (_a = this.collectingPromise) == null ? void 0 : _a.resolve(); + this.collectingPromise = void 0; + } + async getPaths() { + var _a; + await ((_a = this.collectingPromise) == null ? void 0 : _a.promise); + return Array.from(this.pathsSet); + } + getFiles(keys) { + if (keys) + return keys.map((key) => this.filesMap.get(key)).filter(Boolean); + return Array.from(this.filesMap.values()); + } + getFilepaths() { + return Array.from(this.filesMap.keys()); + } + getFailedFilepaths() { + return this.getFiles().filter((i) => { + var _a; + return ((_a = i.result) == null ? void 0 : _a.state) === "fail"; + }).map((i) => i.filepath); + } + collectPaths(paths = []) { + paths.forEach((path) => { + this.pathsSet.add(path); + }); + } + collectFiles(files = []) { + files.forEach((file) => { + this.filesMap.set(file.filepath, file); + this.updateId(file); + }); + } + clearFiles(paths = []) { + paths.forEach((path) => { + this.filesMap.delete(path); + }); + } + updateId(task) { + if (this.idMap.get(task.id) === task) + return; + this.idMap.set(task.id, task); + if (task.type === "suite") { + task.tasks.forEach((task2) => { + this.updateId(task2); + }); + } + } + updateTasks(packs) { + for (const [id, result] of packs) { + if (this.idMap.has(id)) + this.idMap.get(id).result = result; + } + } + updateUserLog(log) { + const task = log.taskId && this.idMap.get(log.taskId); + if (task) { + if (!task.logs) + task.logs = []; + task.logs.push(log); + } + } +} + +const defaultInclude = ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"]; +const defaultExclude = ["**/node_modules/**", "**/dist/**", "**/cypress/**", "**/.{idea,git,cache,output,temp}/**", "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*"]; +const benchmarkConfigDefaults = { + include: ["**/*.{bench,benchmark}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"], + exclude: defaultExclude, + includeSource: [], + reporters: ["default"] +}; +const defaultCoverageExcludes = [ + "coverage/**", + "dist/**", + "packages/*/test{,s}/**", + "**/*.d.ts", + "cypress/**", + "test{,s}/**", + "test{,-*}.{js,cjs,mjs,ts,tsx,jsx}", + "**/*{.,-}test.{js,cjs,mjs,ts,tsx,jsx}", + "**/*{.,-}spec.{js,cjs,mjs,ts,tsx,jsx}", + "**/__tests__/**", + "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*", + "**/.{eslint,mocha,prettier}rc.{js,cjs,yml}" +]; +const coverageConfigDefaults = { + all: false, + provider: "c8", + enabled: false, + clean: true, + cleanOnRerun: true, + reportsDirectory: "./coverage", + excludeNodeModules: true, + exclude: defaultCoverageExcludes, + reporter: ["text", "html", "clover", "json"], + allowExternal: false, + extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"] +}; +const fakeTimersDefaults = { + loopLimit: 1e4, + shouldClearNativeTimers: true, + toFake: [ + "setTimeout", + "clearTimeout", + "setInterval", + "clearInterval", + "setImmediate", + "clearImmediate", + "Date" + ] +}; +const config = { + allowOnly: !process.env.CI, + watch: !process.env.CI, + globals: false, + environment: "node", + threads: true, + clearMocks: false, + restoreMocks: false, + mockReset: false, + include: defaultInclude, + exclude: defaultExclude, + testTimeout: 5e3, + hookTimeout: 1e4, + teardownTimeout: 1e3, + isolate: true, + watchExclude: ["**/node_modules/**", "**/dist/**"], + forceRerunTriggers: [ + "**/package.json/**", + "**/{vitest,vite}.config.*/**" + ], + update: false, + reporters: [], + silent: false, + api: false, + ui: false, + uiBase: "/__vitest__/", + open: true, + css: { + include: [] + }, + coverage: coverageConfigDefaults, + fakeTimers: fakeTimersDefaults, + maxConcurrency: 5, + dangerouslyIgnoreUnhandledErrors: false, + typecheck: { + checker: "tsc", + include: ["**/*.{test,spec}-d.{ts,js}"], + exclude: defaultExclude + }, + slowTestThreshold: 300 +}; +const configDefaults = Object.freeze(config); + +class FilesStatsCache { + constructor() { + this.cache = /* @__PURE__ */ new Map(); + } + getStats(fsPath) { + return this.cache.get(fsPath); + } + async updateStats(fsPath) { + if (!fs$8.existsSync(fsPath)) + return; + const stats = await fs$8.promises.stat(fsPath); + this.cache.set(fsPath, { size: stats.size }); + } + removeStats(fsPath) { + this.cache.delete(fsPath); + } +} + +class ResultsCache { + constructor() { + this.cache = /* @__PURE__ */ new Map(); + this.cachePath = null; + this.version = version$1; + this.root = "/"; + } + getCachePath() { + return this.cachePath; + } + setConfig(root, config) { + this.root = root; + if (config) + this.cachePath = resolve(config.dir, "results.json"); + } + getResults(fsPath) { + return this.cache.get(fsPath == null ? void 0 : fsPath.slice(this.root.length)); + } + async readFromCache() { + if (!this.cachePath) + return; + if (fs$8.existsSync(this.cachePath)) { + const resultsCache = await fs$8.promises.readFile(this.cachePath, "utf8"); + const { results, version: version2 } = JSON.parse(resultsCache); + this.cache = new Map(results); + this.version = version2; + } + } + updateResults(files) { + files.forEach((file) => { + var _a; + const result = file.result; + if (!result) + return; + const duration = result.duration || 0; + const relativePath = (_a = file.filepath) == null ? void 0 : _a.slice(this.root.length); + this.cache.set(relativePath, { + duration: duration >= 0 ? duration : 0, + failed: result.state === "fail" + }); + }); + } + removeFromCache(filepath) { + this.cache.delete(filepath); + } + async writeToCache() { + if (!this.cachePath) + return; + const results = Array.from(this.cache.entries()); + const cacheDirname = dirname(this.cachePath); + if (!fs$8.existsSync(cacheDirname)) + await fs$8.promises.mkdir(cacheDirname, { recursive: true }); + const cache = JSON.stringify({ + version: this.version, + results + }); + await fs$8.promises.writeFile(this.cachePath, cache); + } +} + +class VitestCache { + constructor() { + this.results = new ResultsCache(); + this.stats = new FilesStatsCache(); + } + getFileTestResults(id) { + return this.results.getResults(id); + } + getFileStats(id) { + return this.stats.getStats(id); + } + static resolveCacheDir(root, dir) { + return resolve(root, slash$1(dir || "node_modules/.vitest")); + } + static async clearCache(options) { + var _a; + const root = resolve(options.root || process.cwd()); + const configPath = options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root }); + const config = await loadConfigFromFile({ command: "serve", mode: "test" }, configPath); + const cache = (_a = config == null ? void 0 : config.config.test) == null ? void 0 : _a.cache; + if (cache === false) + throw new Error("Cache is disabled"); + const cachePath = VitestCache.resolveCacheDir(root, cache == null ? void 0 : cache.dir); + let cleared = false; + if (fs$8.existsSync(cachePath)) { + fs$8.rmSync(cachePath, { recursive: true, force: true }); + cleared = true; + } + return { dir: cachePath, cleared }; + } +} + +class BaseSequencer { + constructor(ctx) { + this.ctx = ctx; + } + async shard(files) { + const { config } = this.ctx; + const { index, count } = config.shard; + const shardSize = Math.ceil(files.length / count); + const shardStart = shardSize * (index - 1); + const shardEnd = shardSize * index; + return [...files].map((file) => { + const fullPath = resolve(slash$2(config.root), slash$2(file)); + const specPath = fullPath == null ? void 0 : fullPath.slice(config.root.length); + return { + file, + hash: createHash("sha1").update(specPath).digest("hex") + }; + }).sort((a, b) => a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0).slice(shardStart, shardEnd).map(({ file }) => file); + } + async sort(files) { + const cache = this.ctx.cache; + return [...files].sort((a, b) => { + const aState = cache.getFileTestResults(a); + const bState = cache.getFileTestResults(b); + if (!aState || !bState) { + const statsA = cache.getFileStats(a); + const statsB = cache.getFileStats(b); + if (!statsA || !statsB) + return !statsA && statsB ? -1 : !statsB && statsA ? 1 : 0; + return statsB.size - statsA.size; + } + if (aState.failed && !bState.failed) + return -1; + if (!aState.failed && bState.failed) + return 1; + return bState.duration - aState.duration; + }); + } +} + +class RandomSequencer extends BaseSequencer { + async sort(files) { + const { sequence } = this.ctx.config; + const seed = (sequence == null ? void 0 : sequence.seed) ?? Date.now(); + return shuffle(files, seed); + } +} + +const extraInlineDeps = [ + /^(?!.*(?:node_modules)).*\.mjs$/, + /^(?!.*(?:node_modules)).*\.cjs\.js$/, + /vite\w*\/dist\/client\/env.mjs/, + /\/vitest\/dist\//, + /vitest-virtual-\w+\/dist/, + /@vitest\/dist/, + "@nuxt/test-utils" +]; +function resolveApiConfig(options) { + let api; + if ((options.ui || options.browser) && !options.api) + api = { port: defaultPort }; + else if (options.api === true) + api = { port: defaultPort }; + else if (typeof options.api === "number") + api = { port: options.api }; + if (typeof options.api === "object") { + if (api) { + if (options.api.port) + api.port = options.api.port; + if (options.api.strictPort) + api.strictPort = options.api.strictPort; + if (options.api.host) + api.host = options.api.host; + } else { + api = { ...options.api }; + } + } + if (api) { + if (!api.port) + api.port = defaultPort; + } + return api; +} +function resolveConfig(mode, options, viteConfig) { + var _a, _b, _c, _d, _e, _f, _g; + if (options.dom) { + if (((_a = viteConfig.test) == null ? void 0 : _a.environment) != null && viteConfig.test.environment !== "happy-dom") { + console.warn( + c.yellow( + `${c.inverse(c.yellow(" Vitest "))} Your config.test.environment ("${viteConfig.test.environment}") conflicts with --dom flag ("happy-dom"), ignoring "${viteConfig.test.environment}"` + ) + ); + } + options.environment = "happy-dom"; + } + const resolved = { + ...configDefaults, + ...options, + root: viteConfig.root, + mode + }; + if (viteConfig.base !== "/") + resolved.base = viteConfig.base; + if (options.shard) { + if (resolved.watch) + throw new Error("You cannot use --shard option with enabled watch"); + const [indexString, countString] = options.shard.split("/"); + const index = Math.abs(parseInt(indexString, 10)); + const count = Math.abs(parseInt(countString, 10)); + if (isNaN(count) || count <= 0) + throw new Error("--shard must be a positive number"); + if (isNaN(index) || index <= 0 || index > count) + throw new Error("--shard must be a positive number less then "); + resolved.shard = { index, count }; + } + resolved.deps = resolved.deps || {}; + if (resolved.deps.inline !== true) { + const ssrOptions = viteConfig.ssr; + if ((ssrOptions == null ? void 0 : ssrOptions.noExternal) === true && resolved.deps.inline == null) { + resolved.deps.inline = true; + } else { + (_b = resolved.deps).inline ?? (_b.inline = []); + resolved.deps.inline.push(...extraInlineDeps); + } + } + (_c = resolved.deps).registerNodeLoader ?? (_c.registerNodeLoader = false); + resolved.testNamePattern = resolved.testNamePattern ? resolved.testNamePattern instanceof RegExp ? resolved.testNamePattern : new RegExp(resolved.testNamePattern) : void 0; + const CI = !!process.env.CI; + const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT; + resolved.snapshotOptions = { + snapshotFormat: resolved.snapshotFormat || {}, + updateSnapshot: CI && !UPDATE_SNAPSHOT ? "none" : UPDATE_SNAPSHOT ? "all" : "new", + resolveSnapshotPath: options.resolveSnapshotPath + }; + if (options.resolveSnapshotPath) + delete resolved.resolveSnapshotPath; + if (process.env.VITEST_MAX_THREADS) + resolved.maxThreads = parseInt(process.env.VITEST_MAX_THREADS); + if (process.env.VITEST_MIN_THREADS) + resolved.minThreads = parseInt(process.env.VITEST_MIN_THREADS); + if (mode === "benchmark") { + resolved.benchmark = { + ...benchmarkConfigDefaults, + ...resolved.benchmark + }; + resolved.coverage.enabled = false; + resolved.include = resolved.benchmark.include; + resolved.exclude = resolved.benchmark.exclude; + resolved.includeSource = resolved.benchmark.includeSource; + const reporters = Array.from(/* @__PURE__ */ new Set([ + ...toArray(resolved.benchmark.reporters), + ...toArray(options.reporter) + ])).filter(Boolean); + if (reporters.length) + resolved.benchmark.reporters = reporters; + else + resolved.benchmark.reporters = ["default"]; + if (options.outputFile) + resolved.benchmark.outputFile = options.outputFile; + } + resolved.setupFiles = toArray(resolved.setupFiles || []).map( + (file) => normalize( + resolveModule(file, { paths: [resolved.root] }) ?? resolve(resolved.root, file) + ) + ); + resolved.api = resolveApiConfig(options); + if (options.related) + resolved.related = toArray(options.related).map((file) => resolve(resolved.root, file)); + if (mode !== "benchmark") { + const reporters = resolved.reporter ?? resolved.reporters; + resolved.reporters = Array.from(new Set(toArray(reporters))).filter(Boolean); + } + if (!resolved.reporters.length) + resolved.reporters.push("default"); + if (resolved.changed) + resolved.passWithNoTests ?? (resolved.passWithNoTests = true); + resolved.css ?? (resolved.css = {}); + if (typeof resolved.css === "object") { + (_d = resolved.css).modules ?? (_d.modules = {}); + (_e = resolved.css.modules).classNameStrategy ?? (_e.classNameStrategy = "stable"); + } + resolved.cache ?? (resolved.cache = { dir: "" }); + if (resolved.cache) + resolved.cache.dir = VitestCache.resolveCacheDir(resolved.root, resolved.cache.dir); + resolved.sequence ?? (resolved.sequence = {}); + if (!((_f = resolved.sequence) == null ? void 0 : _f.sequencer)) { + resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer; + } + (_g = resolved.sequence).hooks ?? (_g.hooks = "parallel"); + resolved.typecheck = { + ...configDefaults.typecheck, + ...resolved.typecheck + }; + if (mode === "typecheck") { + resolved.include = resolved.typecheck.include; + resolved.exclude = resolved.typecheck.exclude; + } + return resolved; +} + +const ESC = '\u001B['; +const OSC = '\u001B]'; +const BEL = '\u0007'; +const SEP = ';'; +const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal'; + +const ansiEscapes = {}; + +ansiEscapes.cursorTo = (x, y) => { + if (typeof x !== 'number') { + throw new TypeError('The `x` argument is required'); + } + + if (typeof y !== 'number') { + return ESC + (x + 1) + 'G'; + } + + return ESC + (y + 1) + ';' + (x + 1) + 'H'; +}; + +ansiEscapes.cursorMove = (x, y) => { + if (typeof x !== 'number') { + throw new TypeError('The `x` argument is required'); + } + + let returnValue = ''; + + if (x < 0) { + returnValue += ESC + (-x) + 'D'; + } else if (x > 0) { + returnValue += ESC + x + 'C'; + } + + if (y < 0) { + returnValue += ESC + (-y) + 'A'; + } else if (y > 0) { + returnValue += ESC + y + 'B'; + } + + return returnValue; +}; + +ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A'; +ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B'; +ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C'; +ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D'; + +ansiEscapes.cursorLeft = ESC + 'G'; +ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC + 's'; +ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC + 'u'; +ansiEscapes.cursorGetPosition = ESC + '6n'; +ansiEscapes.cursorNextLine = ESC + 'E'; +ansiEscapes.cursorPrevLine = ESC + 'F'; +ansiEscapes.cursorHide = ESC + '?25l'; +ansiEscapes.cursorShow = ESC + '?25h'; + +ansiEscapes.eraseLines = count => { + let clear = ''; + + for (let i = 0; i < count; i++) { + clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : ''); + } + + if (count) { + clear += ansiEscapes.cursorLeft; + } + + return clear; +}; + +ansiEscapes.eraseEndLine = ESC + 'K'; +ansiEscapes.eraseStartLine = ESC + '1K'; +ansiEscapes.eraseLine = ESC + '2K'; +ansiEscapes.eraseDown = ESC + 'J'; +ansiEscapes.eraseUp = ESC + '1J'; +ansiEscapes.eraseScreen = ESC + '2J'; +ansiEscapes.scrollUp = ESC + 'S'; +ansiEscapes.scrollDown = ESC + 'T'; + +ansiEscapes.clearScreen = '\u001Bc'; + +ansiEscapes.clearTerminal = process.platform === 'win32' ? + `${ansiEscapes.eraseScreen}${ESC}0f` : + // 1. Erases the screen (Only done in case `2` is not supported) + // 2. Erases the whole screen including scrollback buffer + // 3. Moves cursor to the top-left position + // More info: https://www.real-world-systems.com/docs/ANSIcode.html + `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`; + +ansiEscapes.beep = BEL; + +ansiEscapes.link = (text, url) => { + return [ + OSC, + '8', + SEP, + SEP, + url, + BEL, + text, + OSC, + '8', + SEP, + SEP, + BEL + ].join(''); +}; + +ansiEscapes.image = (buffer, options = {}) => { + let returnValue = `${OSC}1337;File=inline=1`; + + if (options.width) { + returnValue += `;width=${options.width}`; + } + + if (options.height) { + returnValue += `;height=${options.height}`; + } + + if (options.preserveAspectRatio === false) { + returnValue += ';preserveAspectRatio=0'; + } + + return returnValue + ':' + buffer.toString('base64') + BEL; +}; + +ansiEscapes.iTerm = { + setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`, + + annotation: (message, options = {}) => { + let returnValue = `${OSC}1337;`; + + const hasX = typeof options.x !== 'undefined'; + const hasY = typeof options.y !== 'undefined'; + if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) { + throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined'); + } + + message = message.replace(/\|/g, ''); + + returnValue += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation='; + + if (options.length > 0) { + returnValue += + (hasX ? + [message, options.length, options.x, options.y] : + [options.length, message]).join('|'); + } else { + returnValue += message; + } + + return returnValue + BEL; + } +}; + +const restoreCursor = onetime.exports(() => { + signalExit.exports(() => { + process$1.stderr.write('\u001B[?25h'); + }, {alwaysLast: true}); +}); + +let isHidden = false; + +const cliCursor = {}; + +cliCursor.show = (writableStream = process$1.stderr) => { + if (!writableStream.isTTY) { + return; + } + + isHidden = false; + writableStream.write('\u001B[?25h'); +}; + +cliCursor.hide = (writableStream = process$1.stderr) => { + if (!writableStream.isTTY) { + return; + } + + restoreCursor(); + isHidden = true; + writableStream.write('\u001B[?25l'); +}; + +cliCursor.toggle = (force, writableStream) => { + if (force !== undefined) { + isHidden = force; + } + + if (isHidden) { + cliCursor.show(writableStream); + } else { + cliCursor.hide(writableStream); + } +}; + +const ESCAPES = new Set([ + '\u001B', + '\u009B', +]); + +const END_CODE = 39; +const ANSI_ESCAPE_BELL = '\u0007'; +const ANSI_CSI = '['; +const ANSI_OSC = ']'; +const ANSI_SGR_TERMINATOR = 'm'; +const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; + +const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; +const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; + +// Calculate the length of words split on ' ', ignoring +// the extra characters added by ansi escape codes +const wordLengths = string => string.split(' ').map(character => stringWidth(character)); + +// Wrap a long word across multiple rows +// Ansi escape codes do not count towards length +const wrapWord = (rows, word, columns) => { + const characters = [...word]; + + let isInsideEscape = false; + let isInsideLinkEscape = false; + let visible = stringWidth(stripAnsi(rows[rows.length - 1])); + + for (const [index, character] of characters.entries()) { + const characterLength = stringWidth(character); + + if (visible + characterLength <= columns) { + rows[rows.length - 1] += character; + } else { + rows.push(character); + visible = 0; + } + + if (ESCAPES.has(character)) { + isInsideEscape = true; + isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); + } + + if (isInsideEscape) { + if (isInsideLinkEscape) { + if (character === ANSI_ESCAPE_BELL) { + isInsideEscape = false; + isInsideLinkEscape = false; + } + } else if (character === ANSI_SGR_TERMINATOR) { + isInsideEscape = false; + } + + continue; + } + + visible += characterLength; + + if (visible === columns && index < characters.length - 1) { + rows.push(''); + visible = 0; + } + } + + // It's possible that the last row we copy over is only + // ansi escape characters, handle this edge-case + if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } +}; + +// Trims spaces from a string ignoring invisible sequences +const stringVisibleTrimSpacesRight = string => { + const words = string.split(' '); + let last = words.length; + + while (last > 0) { + if (stringWidth(words[last - 1]) > 0) { + break; + } + + last--; + } + + if (last === words.length) { + return string; + } + + return words.slice(0, last).join(' ') + words.slice(last).join(''); +}; + +// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode +// +// 'hard' will never allow a string to take up more than columns characters +// +// 'soft' allows long words to expand past the column length +const exec = (string, columns, options = {}) => { + if (options.trim !== false && string.trim() === '') { + return ''; + } + + let returnValue = ''; + let escapeCode; + let escapeUrl; + + const lengths = wordLengths(string); + let rows = ['']; + + for (const [index, word] of string.split(' ').entries()) { + if (options.trim !== false) { + rows[rows.length - 1] = rows[rows.length - 1].trimStart(); + } + + let rowLength = stringWidth(rows[rows.length - 1]); + + if (index !== 0) { + if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { + // If we start with a new word but the current row length equals the length of the columns, add a new row + rows.push(''); + rowLength = 0; + } + + if (rowLength > 0 || options.trim === false) { + rows[rows.length - 1] += ' '; + rowLength++; + } + } + + // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' + if (options.hard && lengths[index] > columns) { + const remainingColumns = (columns - rowLength); + const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); + const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); + if (breaksStartingNextLine < breaksStartingThisLine) { + rows.push(''); + } + + wrapWord(rows, word, columns); + continue; + } + + if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { + if (options.wordWrap === false && rowLength < columns) { + wrapWord(rows, word, columns); + continue; + } + + rows.push(''); + } + + if (rowLength + lengths[index] > columns && options.wordWrap === false) { + wrapWord(rows, word, columns); + continue; + } + + rows[rows.length - 1] += word; + } + + if (options.trim !== false) { + rows = rows.map(row => stringVisibleTrimSpacesRight(row)); + } + + const pre = [...rows.join('\n')]; + + for (const [index, character] of pre.entries()) { + returnValue += character; + + if (ESCAPES.has(character)) { + const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; + if (groups.code !== undefined) { + const code = Number.parseFloat(groups.code); + escapeCode = code === END_CODE ? undefined : code; + } else if (groups.uri !== undefined) { + escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; + } + } + + const code = ansiStyles.codes.get(Number(escapeCode)); + + if (pre[index + 1] === '\n') { + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(''); + } + + if (escapeCode && code) { + returnValue += wrapAnsiCode(code); + } + } else if (character === '\n') { + if (escapeCode && code) { + returnValue += wrapAnsiCode(escapeCode); + } + + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(escapeUrl); + } + } + } + + return returnValue; +}; + +// For each newline, invoke the method separately +function wrapAnsi(string, columns, options) { + return String(string) + .normalize() + .replace(/\r\n/g, '\n') + .split('\n') + .map(line => exec(line, columns, options)) + .join('\n'); +} + +const defaultTerminalHeight = 24; + +const getWidth = stream => { + const {columns} = stream; + + if (!columns) { + return 80; + } + + return columns; +}; + +const fitToTerminalHeight = (stream, text) => { + const terminalHeight = stream.rows || defaultTerminalHeight; + const lines = text.split('\n'); + + const toRemove = lines.length - terminalHeight; + if (toRemove <= 0) { + return text; + } + + return sliceAnsi( + text, + stripAnsi(lines.slice(0, toRemove).join('\n')).length + 1, + ); +}; + +function createLogUpdate(stream, {showCursor = false} = {}) { + let previousLineCount = 0; + let previousWidth = getWidth(stream); + let previousOutput = ''; + + const render = (...arguments_) => { + if (!showCursor) { + cliCursor.hide(); + } + + let output = arguments_.join(' ') + '\n'; + output = fitToTerminalHeight(stream, output); + const width = getWidth(stream); + if (output === previousOutput && previousWidth === width) { + return; + } + + previousOutput = output; + previousWidth = width; + output = wrapAnsi(output, width, { + trim: false, + hard: true, + wordWrap: false, + }); + stream.write(ansiEscapes.eraseLines(previousLineCount) + output); + previousLineCount = output.split('\n').length; + }; + + render.clear = () => { + stream.write(ansiEscapes.eraseLines(previousLineCount)); + previousOutput = ''; + previousWidth = getWidth(stream); + previousLineCount = 0; + }; + + render.done = () => { + previousOutput = ''; + previousWidth = getWidth(stream); + previousLineCount = 0; + + if (!showCursor) { + cliCursor.show(); + } + }; + + return render; +} + +createLogUpdate(process$1.stdout); + +createLogUpdate(process$1.stderr); + +var version = "0.27.0"; + +function formatLine(line, outputTruncateLength) { + var _a; + return cliTruncate(line, (outputTruncateLength ?? (((_a = process.stdout) == null ? void 0 : _a.columns) || 80)) - 4); +} +function unifiedDiff(actual, expected, options = {}) { + if (actual === expected) + return ""; + const { outputTruncateLength, outputDiffLines, outputDiffMaxLines, noColor, showLegend = true } = options; + const indent = " "; + const diffLimit = outputDiffLines || 15; + const diffMaxLines = outputDiffMaxLines || 50; + const counts = { + "+": 0, + "-": 0 + }; + let previousState = null; + let previousCount = 0; + const str = (str2) => str2; + const dim = noColor ? str : c.dim; + const green = noColor ? str : c.green; + const red = noColor ? str : c.red; + function preprocess(line) { + if (!line || line.match(/\\ No newline/)) + return; + const char = line[0]; + if ("-+".includes(char)) { + if (previousState !== char) { + previousState = char; + previousCount = 0; + } + previousCount++; + counts[char]++; + if (previousCount === diffLimit) + return dim(`${char} ...`); + else if (previousCount > diffLimit) + return; + } + return line; + } + const msg = createPatch("string", expected, actual); + let lines = msg.split("\n").slice(5).map(preprocess).filter(Boolean); + let moreLines = 0; + const isCompact = counts["+"] === 1 && counts["-"] === 1 && lines.length === 2; + if (lines.length > diffMaxLines) { + const firstDiff = lines.findIndex((line) => line[0] === "-" || line[0] === "+"); + const displayLines = lines.slice(firstDiff - 2, diffMaxLines); + const lastDisplayedIndex = firstDiff - 2 + diffMaxLines; + if (lastDisplayedIndex < lines.length) + moreLines = lines.length - lastDisplayedIndex; + lines = displayLines; + } + let formatted = lines.map((line) => { + line = line.replace(/\\"/g, '"'); + if (line[0] === "-") { + line = formatLine(line.slice(1), outputTruncateLength); + if (isCompact) + return green(line); + return green(`- ${formatLine(line, outputTruncateLength)}`); + } + if (line[0] === "+") { + line = formatLine(line.slice(1), outputTruncateLength); + if (isCompact) + return red(line); + return red(`+ ${formatLine(line, outputTruncateLength)}`); + } + if (line.match(/@@/)) + return "--"; + return ` ${line}`; + }); + if (moreLines) + formatted.push(dim(`... ${moreLines} more lines`)); + if (showLegend) { + if (isCompact) { + formatted = [ + `${green("- Expected")} ${formatted[0]}`, + `${red("+ Received")} ${formatted[1]}` + ]; + } else { + if (formatted[0].includes('"')) + formatted[0] = formatted[0].replace('"', ""); + const last = formatted.length - 1; + if (formatted[last].endsWith('"')) + formatted[last] = formatted[last].slice(0, formatted[last].length - 1); + formatted.unshift( + green(`- Expected - ${counts["-"]}`), + red(`+ Received + ${counts["+"]}`), + "" + ); + } + } + return formatted.map((i) => i ? indent + i : i).join("\n"); +} + +async function printError(error, ctx, options = {}) { + const { showCodeFrame = true, fullStack = false, type } = options; + let e = error; + if (typeof error === "string") { + e = { + message: error.split(/\n/g)[0], + stack: error + }; + } + if (!e) { + const error2 = new Error("unknown error"); + e = { + message: e ?? error2.message, + stack: error2.stack + }; + } + const stacks = parseStacktrace(e, fullStack); + const nearest = error instanceof TypeCheckError ? error.stacks[0] : stacks.find( + (stack) => ctx.server.moduleGraph.getModuleById(stack.file) && existsSync$1(stack.file) + ); + const errorProperties = getErrorProperties(e); + if (type) + printErrorType(type, ctx); + printErrorMessage(e, ctx.logger); + if (e.frame) { + ctx.logger.error(c.yellow(e.frame)); + } else { + printStack(ctx, stacks, nearest, errorProperties, (s) => { + if (showCodeFrame && s === nearest && nearest) { + const sourceCode = readFileSync(nearest.file, "utf-8"); + ctx.logger.error(c.yellow(generateCodeFrame(sourceCode, 4, s.line, s.column))); + } + }); + } + if (typeof e.cause === "object" && e.cause && "name" in e.cause) { + e.cause.name = `Caused by: ${e.cause.name}`; + await printError(e.cause, ctx, { fullStack, showCodeFrame: false }); + } + handleImportOutsideModuleError(e.stack || e.stackStr || "", ctx); + if (e.showDiff || e.showDiff === void 0 && e.actual && e.expected) { + displayDiff(stringify$5(e.actual), stringify$5(e.expected), ctx.logger.console, { + outputTruncateLength: ctx.config.outputTruncateLength, + outputDiffLines: ctx.config.outputDiffLines, + outputDiffMaxLines: ctx.config.outputDiffMaxLines + }); + } +} +function printErrorType(type, ctx) { + ctx.logger.error(` +${c.red(divider(c.bold(c.inverse(` ${type} `))))}`); +} +const skipErrorProperties = /* @__PURE__ */ new Set([ + "nameStr", + "stack", + "cause", + "stacks", + "stackStr", + "type", + "showDiff", + "actual", + "expected", + ...Object.getOwnPropertyNames(Error.prototype), + ...Object.getOwnPropertyNames(Object.prototype) +]); +function getErrorProperties(e) { + const errorObject = /* @__PURE__ */ Object.create(null); + if (e.name === "AssertionError") + return errorObject; + for (const key of Object.getOwnPropertyNames(e)) { + if (!skipErrorProperties.has(key)) + errorObject[key] = e[key]; + } + return errorObject; +} +const esmErrors = [ + "Cannot use import statement outside a module", + "Unexpected token 'export'" +]; +function handleImportOutsideModuleError(stack, ctx) { + if (!esmErrors.some((e) => stack.includes(e))) + return; + const path = normalize(stack.split("\n")[0].trim()); + let name = path.split("/node_modules/").pop() || ""; + if (name == null ? void 0 : name.startsWith("@")) + name = name.split("/").slice(0, 2).join("/"); + else + name = name.split("/")[0]; + ctx.logger.error(c.yellow( + `Module ${path} seems to be an ES Module but shipped in a CommonJS package. You might want to create an issue to the package ${c.bold(`"${name}"`)} asking them to ship the file in .mjs extension or add "type": "module" in their package.json. + +As a temporary workaround you can try to inline the package by updating your config: + +` + c.gray(c.dim("// vitest.config.js")) + "\n" + c.green(`export default { + test: { + deps: { + inline: [ + ${c.yellow(c.bold(`"${name}"`))} + ] + } + } +} +`) + )); +} +function displayDiff(actual, expected, console, options = {}) { + const diff = unifiedDiff(actual, expected, options); + const dim = options.noColor ? (s) => s : c.dim; + const black = options.noColor ? (s) => s : c.black; + if (diff) + console.error(diff + "\n"); + else if (actual && expected && actual !== '"undefined"' && expected !== '"undefined"') + console.error(dim("Could not display diff. It's possible objects are too large to compare.\nTry increasing ") + black("--outputDiffMaxSize") + dim(" option.\n")); +} +function printErrorMessage(error, logger) { + const errorName = error.name || error.nameStr || "Unknown Error"; + logger.error(c.red(`${c.bold(errorName)}: ${error.message}`)); +} +function printStack(ctx, stack, highlight, errorProperties, onStack) { + if (!stack.length) + return; + const logger = ctx.logger; + for (const frame of stack) { + const color = frame === highlight ? c.yellow : c.gray; + const path = relative(ctx.config.root, frame.file); + logger.error(color(` ${c.dim(F_POINTER)} ${[frame.method, c.dim(`${path}:${frame.line}:${frame.column}`)].filter(Boolean).join(" ")}`)); + onStack == null ? void 0 : onStack(frame); + if (frame.file in ctx.state.filesMap) + break; + } + logger.error(); + const hasProperties = Object.keys(errorProperties).length > 0; + if (hasProperties) { + logger.error(c.red(c.dim(divider()))); + const propertiesString = stringify$5(errorProperties, 10, { printBasicPrototype: false }); + logger.error(c.red(c.bold("Serialized Error:")), c.gray(propertiesString)); + } +} +function generateCodeFrame(source, indent = 0, lineNumber, columnNumber, range = 2) { + var _a; + const start = positionToOffset(source, lineNumber, columnNumber); + const end = start; + const lines = source.split(lineSplitRE); + let count = 0; + let res = []; + const columns = ((_a = process.stdout) == null ? void 0 : _a.columns) || 80; + function lineNo(no = "") { + return c.gray(`${String(no).padStart(3, " ")}| `); + } + for (let i = 0; i < lines.length; i++) { + count += lines[i].length + 1; + if (count >= start) { + for (let j = i - range; j <= i + range || end > count; j++) { + if (j < 0 || j >= lines.length) + continue; + const lineLength = lines[j].length; + if (lineLength > 200) + return ""; + res.push(lineNo(j + 1) + cliTruncate(lines[j].replace(/\t/g, " "), columns - 5 - indent)); + if (j === i) { + const pad = start - (count - lineLength); + const length = Math.max(1, end > count ? lineLength - pad : end - start); + res.push(lineNo() + " ".repeat(pad) + c.red("^".repeat(length))); + } else if (j > i) { + if (end > count) { + const length = Math.max(1, Math.min(end - count, lineLength)); + res.push(lineNo() + c.red("^".repeat(length))); + } + count += lineLength + 1; + } + } + break; + } + } + if (indent) + res = res.map((line) => " ".repeat(indent) + line); + return res.join("\n"); +} + +class Logger { + constructor(ctx, console = globalThis.console) { + this.ctx = ctx; + this.console = console; + this.outputStream = process.stdout; + this.errorStream = process.stderr; + this.logUpdate = createLogUpdate(process.stdout); + } + log(...args) { + this._clearScreen(); + this.console.log(...args); + } + error(...args) { + this._clearScreen(); + this.console.error(...args); + } + warn(...args) { + this._clearScreen(); + this.console.warn(...args); + } + clearFullScreen(message) { + if (this.ctx.server.config.clearScreen === false) { + this.console.log(message); + return; + } + this.console.log(`\x1Bc${message}`); + } + clearScreen(message, force = false) { + if (this.ctx.server.config.clearScreen === false) { + this.console.log(message); + return; + } + this._clearScreenPending = message; + if (force) + this._clearScreen(); + } + _clearScreen() { + if (this._clearScreenPending == null) + return; + const log = this._clearScreenPending; + this._clearScreenPending = void 0; + this.console.log(`\x1B[1;1H\x1B[J${log}`); + } + printError(err, fullStack = false, type) { + return printError(err, this.ctx, { + fullStack, + type, + showCodeFrame: true + }); + } + printNoTestFound(filters) { + const config = this.ctx.config; + const comma = c.dim(", "); + if (filters == null ? void 0 : filters.length) + this.console.error(c.dim("filter: ") + c.yellow(filters.join(comma))); + if (config.include) + this.console.error(c.dim("include: ") + c.yellow(config.include.join(comma))); + if (config.exclude) + this.console.error(c.dim("exclude: ") + c.yellow(config.exclude.join(comma))); + if (config.watchExclude) + this.console.error(c.dim("watch exclude: ") + c.yellow(config.watchExclude.join(comma))); + if (config.passWithNoTests) + this.log(`No ${config.mode} files found, exiting with code 0 +`); + else + this.error(c.red(` +No ${config.mode} files found, exiting with code 1`)); + } + printBanner() { + var _a, _b, _c; + this.log(); + const versionTest = this.ctx.config.watch ? c.blue(`v${version}`) : c.cyan(`v${version}`); + const mode = this.ctx.config.watch ? c.blue(" DEV ") : c.cyan(" RUN "); + this.log(`${c.inverse(c.bold(mode))} ${versionTest} ${c.gray(this.ctx.config.root)}`); + if (this.ctx.config.browser) + this.log(c.dim(c.green(` Browser runner started at http://${((_a = this.ctx.config.api) == null ? void 0 : _a.host) || "localhost"}:${c.bold(`${this.ctx.server.config.server.port}`)}`))); + else if (this.ctx.config.ui) + this.log(c.dim(c.green(` UI started at http://${((_b = this.ctx.config.api) == null ? void 0 : _b.host) || "localhost"}:${c.bold(`${this.ctx.server.config.server.port}`)}${this.ctx.config.uiBase}`))); + else if (this.ctx.config.api) + this.log(c.dim(c.green(` API started at http://${((_c = this.ctx.config.api) == null ? void 0 : _c.host) || "localhost"}:${c.bold(`${this.ctx.config.api.port}`)}`))); + if (this.ctx.coverageProvider) + this.log(c.dim(" Coverage enabled with ") + c.yellow(this.ctx.coverageProvider.name)); + this.log(); + } + async printUnhandledErrors(errors) { + const errorMessage = c.red(c.bold( + ` +Vitest caught ${errors.length} unhandled error${errors.length > 1 ? "s" : ""} during the test run. +This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected.` + )); + this.log(c.red(divider(c.bold(c.inverse(" Unhandled Errors "))))); + this.log(errorMessage); + await Promise.all(errors.map(async (err) => { + await this.printError(err, true, err.type || "Unhandled Error"); + })); + this.log(c.red(divider())); + } + async printSourceTypeErrors(errors) { + const errorMessage = c.red(c.bold( + ` +Vitest found ${errors.length} error${errors.length > 1 ? "s" : ""} not related to your test files.` + )); + this.log(c.red(divider(c.bold(c.inverse(" Source Errors "))))); + this.log(errorMessage); + await Promise.all(errors.map(async (err) => { + await this.printError(err, true); + })); + this.log(c.red(divider())); + } +} + +const WATCHER_DEBOUNCE = 100; +class Vitest { + constructor(mode) { + this.mode = mode; + this.config = void 0; + this.server = void 0; + this.state = void 0; + this.snapshot = void 0; + this.cache = void 0; + this.reporters = void 0; + this.vitenode = void 0; + this.invalidates = /* @__PURE__ */ new Set(); + this.changedTests = /* @__PURE__ */ new Set(); + this.isFirstRun = true; + this.restartsCount = 0; + this.runner = void 0; + this._onRestartListeners = []; + this._onSetServer = []; + this.unregisterWatcher = noop$1; + this.logger = new Logger(this); + } + async setServer(options, server) { + var _a, _b, _c; + (_a = this.unregisterWatcher) == null ? void 0 : _a.call(this); + safeClearTimeout(this._rerunTimer); + this.restartsCount += 1; + (_b = this.pool) == null ? void 0 : _b.close(); + this.pool = void 0; + const resolved = resolveConfig(this.mode, options, server.config); + this.server = server; + this.config = resolved; + this.state = new StateManager(); + this.cache = new VitestCache(); + this.snapshot = new SnapshotManager({ ...resolved.snapshotOptions }); + if (this.config.watch && this.mode !== "typecheck") + this.registerWatcher(); + this.vitenode = new ViteNodeServer(server, this.config); + const node = this.vitenode; + this.runner = new ViteNodeRunner({ + root: server.config.root, + base: server.config.base, + fetchModule(id) { + return node.fetchModule(id); + }, + resolveId(id, importer) { + return node.resolveId(id, importer); + } + }); + if (this.config.watch) { + const serverRestart = server.restart; + server.restart = async (...args) => { + await Promise.all(this._onRestartListeners.map((fn) => fn())); + return await serverRestart(...args); + }; + server.watcher.on("change", async (file) => { + file = normalizePath(file); + const isConfig = file === server.config.configFile; + if (isConfig) { + await Promise.all(this._onRestartListeners.map((fn) => fn("config"))); + await serverRestart(); + } + }); + } + this.reporters = resolved.mode === "benchmark" ? await createBenchmarkReporters(toArray((_c = resolved.benchmark) == null ? void 0 : _c.reporters), this.runner) : await createReporters(resolved.reporters, this.runner); + this.runningPromise = void 0; + this.cache.results.setConfig(resolved.root, resolved.cache); + try { + await this.cache.results.readFromCache(); + } catch { + } + await Promise.all(this._onSetServer.map((fn) => fn())); + } + async initCoverageProvider() { + if (this.coverageProvider !== void 0) + return; + this.coverageProvider = await getCoverageProvider(this.config.coverage); + if (this.coverageProvider) { + await this.coverageProvider.initialize(this); + this.config.coverage = this.coverageProvider.resolveOptions(); + } + return this.coverageProvider; + } + getSerializableConfig() { + return deepMerge( + { + ...this.config, + reporters: [], + snapshotOptions: { + ...this.config.snapshotOptions, + resolveSnapshotPath: void 0 + }, + onConsoleLog: void 0, + sequence: { + ...this.config.sequence, + sequencer: void 0 + }, + benchmark: { + ...this.config.benchmark, + reporters: [] + } + }, + this.configOverride || {} + ); + } + async typecheck(filters = []) { + const { include, exclude } = this.config.typecheck; + const testsFilesList = await this.globFiles(filters, include, exclude); + const checker = new Typechecker(this, testsFilesList); + this.typechecker = checker; + checker.onParseEnd(async ({ files, sourceErrors }) => { + this.state.collectFiles(checker.getTestFiles()); + await this.report("onTaskUpdate", checker.getTestPacks()); + await this.report("onCollected"); + if (!files.length) { + this.logger.printNoTestFound(); + } else { + if (hasFailed(files)) + process.exitCode = 1; + await this.report("onFinished", files); + } + if (sourceErrors.length && !this.config.typecheck.ignoreSourceErrors) { + process.exitCode = 1; + await this.logger.printSourceTypeErrors(sourceErrors); + } + if (!files.length) { + const exitCode = this.config.passWithNoTests ? process.exitCode ?? 0 : 1; + process.exit(exitCode); + } + if (this.config.watch) { + await this.report("onWatcherStart", files, [ + ...sourceErrors, + ...this.state.getUnhandledErrors() + ]); + } + }); + checker.onParseStart(async () => { + await this.report("onInit", this); + this.state.collectFiles(checker.getTestFiles()); + await this.report("onCollected"); + }); + checker.onWatcherRerun(async () => { + await this.report("onWatcherRerun", testsFilesList, "File change detected. Triggering rerun."); + await checker.collectTests(); + this.state.collectFiles(checker.getTestFiles()); + await this.report("onTaskUpdate", checker.getTestPacks()); + await this.report("onCollected"); + }); + await checker.prepare(); + await checker.collectTests(); + await checker.start(); + } + async start(filters) { + var _a; + if (this.mode === "typecheck") { + await this.typecheck(filters); + return; + } + try { + await this.initCoverageProvider(); + await ((_a = this.coverageProvider) == null ? void 0 : _a.clean(this.config.coverage.clean)); + } catch (e) { + this.logger.error(e); + process.exit(1); + } + await this.report("onInit", this); + const files = await this.filterTestsBySource( + await this.globTestFiles(filters) + ); + if (!files.length) { + const exitCode = this.config.passWithNoTests ? 0 : 1; + this.logger.printNoTestFound(filters); + process.exit(exitCode); + } + await Promise.all(files.map((file) => this.cache.stats.updateStats(file))); + await this.runFiles(files); + if (this.coverageProvider) { + this.logger.log(c.blue(" % ") + c.dim("Coverage report from ") + c.yellow(this.coverageProvider.name)); + await this.coverageProvider.reportCoverage(); + } + if (this.config.watch && !this.config.browser) + await this.report("onWatcherStart"); + } + async getTestDependencies(filepath) { + const deps = /* @__PURE__ */ new Set(); + const addImports = async (filepath2) => { + const transformed = await this.vitenode.transformRequest(filepath2); + if (!transformed) + return; + const dependencies = [...transformed.deps || [], ...transformed.dynamicDeps || []]; + for (const dep of dependencies) { + const path = await this.server.pluginContainer.resolveId(dep, filepath2, { ssr: true }); + const fsPath = path && !path.external && path.id.split("?")[0]; + if (fsPath && !fsPath.includes("node_modules") && !deps.has(fsPath) && existsSync(fsPath)) { + deps.add(fsPath); + await addImports(fsPath); + } + } + }; + await addImports(filepath); + return deps; + } + async filterTestsBySource(tests) { + if (this.config.changed && !this.config.related) { + const { VitestGit } = await import('./chunk-node-git.543e964a.js'); + const vitestGit = new VitestGit(this.config.root); + const related2 = await vitestGit.findChangedFiles({ + changedSince: this.config.changed + }); + if (!related2) { + this.logger.error(c.red("Could not find Git root. Have you initialized git with `git init`?\n")); + process.exit(1); + } + this.config.related = Array.from(new Set(related2)); + } + const related = this.config.related; + if (!related) + return tests; + const forceRerunTriggers = this.config.forceRerunTriggers; + if (forceRerunTriggers.length && micromatch_1(related, forceRerunTriggers).length) + return tests; + if (!related.length) + return []; + const testGraphs = await Promise.all( + tests.map(async (filepath) => { + const deps = await this.getTestDependencies(filepath); + return [filepath, deps]; + }) + ); + const runningTests = []; + for (const [filepath, deps] of testGraphs) { + if (related.some((path) => path === filepath || deps.has(path))) + runningTests.push(filepath); + } + return runningTests; + } + async runFiles(paths) { + paths = Array.from(new Set(paths)); + await this.runningPromise; + this.state.startCollectingPaths(); + this.runningPromise = (async () => { + if (!this.pool) + this.pool = createPool(this); + const invalidates = Array.from(this.invalidates); + this.invalidates.clear(); + this.snapshot.clear(); + this.state.clearErrors(); + try { + await this.pool.runTests(paths, invalidates); + } catch (err) { + this.state.catchError(err, "Unhandled Error"); + } + const files = this.state.getFiles(); + if (hasFailed(files)) + process.exitCode = 1; + this.cache.results.updateResults(files); + await this.cache.results.writeToCache(); + })().finally(async () => { + this.state.finishCollectingPaths(); + if (!this.config.browser) + await this.report("onFinished", this.state.getFiles(), this.state.getUnhandledErrors()); + this.runningPromise = void 0; + }); + return await this.runningPromise; + } + async rerunFiles(files = this.state.getFilepaths(), trigger) { + await this.report("onWatcherRerun", files, trigger); + await this.runFiles(files); + if (!this.config.browser) + await this.report("onWatcherStart"); + } + async changeNamePattern(pattern, files = this.state.getFilepaths(), trigger) { + this.config.testNamePattern = pattern ? new RegExp(pattern) : void 0; + await this.rerunFiles(files, trigger); + } + async changeFilenamePattern(pattern) { + const files = this.state.getFilepaths(); + if (!pattern) + return await this.rerunFiles(files, "reset filename pattern"); + const filteredFiles = await this.globTestFiles([pattern]); + await this.rerunFiles(filteredFiles, "change filename pattern"); + } + async rerunFailed() { + await this.rerunFiles(this.state.getFailedFilepaths(), "rerun failed"); + } + async updateSnapshot(files) { + files = files || [ + ...this.state.getFailedFilepaths(), + ...this.snapshot.summary.uncheckedKeysByFile.map((s) => s.filePath) + ]; + this.configOverride = { + snapshotOptions: { + updateSnapshot: "all" + } + }; + try { + await this.rerunFiles(files, "update snapshot"); + } finally { + this.configOverride = void 0; + } + } + async scheduleRerun(triggerId) { + const mod = this.server.moduleGraph.getModuleById(triggerId); + if (mod) + mod.lastHMRTimestamp = Date.now(); + const currentCount = this.restartsCount; + safeClearTimeout(this._rerunTimer); + await this.runningPromise; + safeClearTimeout(this._rerunTimer); + if (this.restartsCount !== currentCount) + return; + this._rerunTimer = safeSetTimeout(async () => { + var _a; + if (this.changedTests.size === 0) { + this.invalidates.clear(); + return; + } + if (this.restartsCount !== currentCount) + return; + this.isFirstRun = false; + this.snapshot.clear(); + const files = Array.from(this.changedTests); + this.changedTests.clear(); + if (this.coverageProvider && this.config.coverage.cleanOnRerun) + await this.coverageProvider.clean(); + await this.report("onWatcherRerun", files, triggerId); + await this.runFiles(files); + await ((_a = this.coverageProvider) == null ? void 0 : _a.reportCoverage()); + if (!this.config.browser) + await this.report("onWatcherStart"); + }, WATCHER_DEBOUNCE); + } + registerWatcher() { + const onChange = (id) => { + id = slash$1(id); + const needsRerun = this.handleFileChanged(id); + if (needsRerun) + this.scheduleRerun(id); + }; + const onUnlink = (id) => { + id = slash$1(id); + this.invalidates.add(id); + if (this.state.filesMap.has(id)) { + this.state.filesMap.delete(id); + this.cache.results.removeFromCache(id); + this.cache.stats.removeStats(id); + this.changedTests.delete(id); + this.report("onTestRemoved", id); + } + }; + const onAdd = async (id) => { + id = slash$1(id); + if (await this.isTargetFile(id)) { + this.changedTests.add(id); + await this.cache.stats.updateStats(id); + this.scheduleRerun(id); + } + }; + const watcher = this.server.watcher; + if (this.config.forceRerunTriggers.length) + watcher.add(this.config.forceRerunTriggers); + watcher.unwatch(this.config.watchExclude); + watcher.on("change", onChange); + watcher.on("unlink", onUnlink); + watcher.on("add", onAdd); + this.unregisterWatcher = () => { + watcher.off("change", onChange); + watcher.off("unlink", onUnlink); + watcher.off("add", onAdd); + this.unregisterWatcher = noop$1; + }; + } + handleFileChanged(id) { + if (this.changedTests.has(id) || this.invalidates.has(id)) + return false; + if (micromatch_1.isMatch(id, this.config.forceRerunTriggers)) { + this.state.getFilepaths().forEach((file) => this.changedTests.add(file)); + return true; + } + const mod = this.server.moduleGraph.getModuleById(id); + if (!mod) + return false; + this.invalidates.add(id); + if (this.state.filesMap.has(id)) { + this.changedTests.add(id); + return true; + } + let rerun = false; + mod.importers.forEach((i) => { + if (!i.id) + return; + const heedsRerun = this.handleFileChanged(i.id); + if (heedsRerun) + rerun = true; + }); + return rerun; + } + async close() { + var _a, _b; + if (!this.closingPromise) { + this.closingPromise = Promise.allSettled([ + (_a = this.pool) == null ? void 0 : _a.close(), + this.server.close(), + (_b = this.typechecker) == null ? void 0 : _b.stop() + ].filter(Boolean)).then((results) => { + results.filter((r) => r.status === "rejected").forEach((err) => { + this.logger.error("error during close", err.reason); + }); + }); + } + return this.closingPromise; + } + async exit(force = false) { + safeSetTimeout(() => { + console.warn(`close timed out after ${this.config.teardownTimeout}ms`); + process.exit(); + }, this.config.teardownTimeout).unref(); + await this.close(); + if (force) + process.exit(); + } + async report(name, ...args) { + await Promise.all(this.reporters.map((r) => { + var _a; + return (_a = r[name]) == null ? void 0 : _a.call( + r, + ...args + ); + })); + } + async globFiles(filters, include, exclude) { + const globOptions = { + absolute: true, + dot: true, + cwd: this.config.dir || this.config.root, + ignore: exclude + }; + let testFiles = await out(include, globOptions); + if (filters.length && process.platform === "win32") + filters = filters.map((f) => toNamespacedPath(f)); + if (filters.length) + testFiles = testFiles.filter((i) => filters.some((f) => i.includes(f))); + return testFiles; + } + async globTestFiles(filters = []) { + const { include, exclude, includeSource } = this.config; + const testFiles = await this.globFiles(filters, include, exclude); + if (includeSource) { + const files = await this.globFiles(filters, includeSource, exclude); + await Promise.all(files.map(async (file) => { + try { + const code = await promises.readFile(file, "utf-8"); + if (this.isInSourceTestFile(code)) + testFiles.push(file); + } catch { + return null; + } + })); + } + return testFiles; + } + async isTargetFile(id, source) { + var _a; + const relativeId = relative(this.config.dir || this.config.root, id); + if (micromatch_1.isMatch(relativeId, this.config.exclude)) + return false; + if (micromatch_1.isMatch(relativeId, this.config.include)) + return true; + if (((_a = this.config.includeSource) == null ? void 0 : _a.length) && micromatch_1.isMatch(relativeId, this.config.includeSource)) { + source = source || await promises.readFile(id, "utf-8"); + return this.isInSourceTestFile(source); + } + return false; + } + isInSourceTestFile(code) { + return code.includes("import.meta.vitest"); + } + onServerRestart(fn) { + this._onRestartListeners.push(fn); + } + onAfterSetServer(fn) { + this._onSetServer.push(fn); + } +} + +function generateCssFilenameHash(filepath) { + return createHash$1("md5").update(filepath).digest("hex").slice(0, 6); +} +function generateScopedClassName(strategy, name, filename) { + if (strategy === "scoped") + return null; + if (strategy === "non-scoped") + return name; + const hash = generateCssFilenameHash(filename); + return `_${name}_${hash}`; +} + +const EnvReplacerPlugin = () => { + return { + name: "vitest:env-replacer", + enforce: "pre", + transform(code, id) { + if (!/\bimport\.meta\.env\b/g.test(code)) + return null; + let s = null; + const envs = stripLiteral(code).matchAll(/\bimport\.meta\.env\b/g); + for (const env of envs) { + s || (s = new MagicString(code)); + const startIndex = env.index; + const endIndex = startIndex + env[0].length; + s.overwrite(startIndex, endIndex, "process.env"); + } + if (s) { + return { + code: s.toString(), + map: s.generateMap({ + hires: true, + source: cleanUrl(id) + }) + }; + } + } + }; +}; + +async function loadGlobalSetupFiles(ctx) { + var _a; + const server = ctx.server; + const runner = ctx.runner; + const globalSetupFiles = toArray((_a = server.config.test) == null ? void 0 : _a.globalSetup); + return Promise.all(globalSetupFiles.map((file) => loadGlobalSetupFile(file, runner))); +} +async function loadGlobalSetupFile(file, runner) { + const m = await runner.executeFile(file); + for (const exp of ["default", "setup", "teardown"]) { + if (m[exp] != null && typeof m[exp] !== "function") + throw new Error(`invalid export in globalSetup file ${file}: ${exp} must be a function`); + } + if (m.default) { + return { + file, + setup: m.default + }; + } else if (m.setup || m.teardown) { + return { + file, + setup: m.setup, + teardown: m.teardown + }; + } else { + throw new Error(`invalid globalSetup file ${file}. Must export setup, teardown or have a default export`); + } +} +const GlobalSetupPlugin = (ctx) => { + let globalSetupFiles; + return { + name: "vitest:global-setup-plugin", + enforce: "pre", + async buildStart() { + var _a, _b; + if (!((_a = ctx.server.config.test) == null ? void 0 : _a.globalSetup)) + return; + globalSetupFiles = await loadGlobalSetupFiles(ctx); + try { + for (const globalSetupFile of globalSetupFiles) { + const teardown = await ((_b = globalSetupFile.setup) == null ? void 0 : _b.call(globalSetupFile)); + if (teardown == null || !!globalSetupFile.teardown) + continue; + if (typeof teardown !== "function") + throw new Error(`invalid return value in globalSetup file ${globalSetupFile.file}. Must return a function`); + globalSetupFile.teardown = teardown; + } + } catch (e) { + ctx.logger.error(` +${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`); + await ctx.logger.printError(e); + process.exit(1); + } + }, + async buildEnd() { + var _a; + if (globalSetupFiles == null ? void 0 : globalSetupFiles.length) { + for (const globalSetupFile of globalSetupFiles.reverse()) { + try { + await ((_a = globalSetupFile.teardown) == null ? void 0 : _a.call(globalSetupFile)); + } catch (error) { + ctx.logger.error(`error during global teardown of ${globalSetupFile.file}`, error); + } + } + } + } + }; +}; + +const hoistRegexp = /^[ \t]*\b((?:vitest|vi)\s*.\s*(mock|unmock)\(["`'\s]+(.*[@\w_-]+)["`'\s]+)[),]{1};?/gm; +const vitestRegexp = /import {[^}]*}.*(?=["'`]vitest["`']).*/gm; +function hoistMocks(code) { + let m; + const mocks = code.matchAll(hoistRegexp); + for (const mockResult of mocks) { + const lastIndex = getMockLastIndex(code.slice(mockResult.index)); + if (lastIndex === null) + continue; + const startIndex = mockResult.index; + const { insideComment, insideString } = getIndexStatus(code, startIndex); + if (insideComment || insideString) + continue; + const endIndex = startIndex + lastIndex; + m ?? (m = new MagicString(code)); + m.prepend(`${m.slice(startIndex, endIndex)} +`); + m.remove(startIndex, endIndex); + } + return m; +} +const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API. +You may encounter this issue when importing the mocks API from another module other than 'vitest'. + +To fix this issue you can either: +- import the mocks API directly from 'vitest' +- enable the 'globals' options`; +const MocksPlugin = () => { + return { + name: "vitest:mock-plugin", + enforce: "post", + async transform(code) { + const m = hoistMocks(code); + if (m) { + const vitestImports = code.matchAll(vitestRegexp); + let found = false; + for (const match of vitestImports) { + const indexStart = match.index; + const indexEnd = match[0].length + indexStart; + m.remove(indexStart, indexEnd); + m.prepend(`${match[0]} +`); + found = true; + } + if (!found) { + m.prepend(`try { vi } catch (_) { try { vitest } catch (__){ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) } } +`); + } + return { + code: m.toString(), + map: m.generateMap({ hires: true }) + }; + } + } + }; +}; +function getMockLastIndex(code) { + const index = getCallLastIndex(code); + if (index === null) + return null; + return code[index + 1] === ";" ? index + 2 : index + 1; +} +function getIndexStatus(code, from) { + let index = 0; + let commentStarted = false; + let commentEnded = true; + let multilineCommentStarted = false; + let multilineCommentEnded = true; + let inString = null; + let beforeChar = null; + while (index <= from) { + const char = code[index]; + const sub = code[index] + code[index + 1]; + if (!inString) { + if (sub === "/*") { + multilineCommentStarted = true; + multilineCommentEnded = false; + } + if (sub === "*/" && multilineCommentStarted) { + multilineCommentStarted = false; + multilineCommentEnded = true; + } + if (sub === "//") { + commentStarted = true; + commentEnded = false; + } + if ((char === "\n" || sub === "\r\n") && commentStarted) { + commentStarted = false; + commentEnded = true; + } + } + if (!multilineCommentStarted && !commentStarted) { + const isCharString = char === '"' || char === "'" || char === "`"; + if (isCharString && beforeChar !== "\\") { + if (inString === char) + inString = null; + else if (!inString) + inString = char; + } + } + beforeChar = char; + index++; + } + return { + insideComment: !multilineCommentEnded || !commentEnded, + insideString: inString !== null + }; +} + +const cssLangs = "\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)"; +const cssLangRE = new RegExp(cssLangs); +const cssModuleRE = new RegExp(`\\.module${cssLangs}`); +const isCSS = (id) => { + return cssLangRE.test(id); +}; +const isCSSModule = (id) => { + return cssModuleRE.test(id); +}; +const getCSSModuleProxyReturn = (strategy, filename) => { + if (strategy === "non-scoped") + return "style"; + const hash = generateCssFilenameHash(filename); + return `\`_\${style}_${hash}\``; +}; +function CSSEnablerPlugin(ctx) { + const shouldProcessCSS = (id) => { + const { css } = ctx.config; + if (typeof css === "boolean") + return css; + if (toArray(css.exclude).some((re) => re.test(id))) + return false; + if (toArray(css.include).some((re) => re.test(id))) + return true; + return false; + }; + return [ + { + name: "vitest:css-disable", + enforce: "pre", + transform(code, id) { + if (!isCSS(id)) + return; + if (!shouldProcessCSS(id)) + return { code: "" }; + } + }, + { + name: "vitest:css-empty-post", + enforce: "post", + transform(_, id) { + var _a; + if (!isCSS(id) || shouldProcessCSS(id)) + return; + if (isCSSModule(id)) { + const scopeStrategy = typeof ctx.config.css !== "boolean" && ((_a = ctx.config.css.modules) == null ? void 0 : _a.classNameStrategy) || "stable"; + const proxyReturn = getCSSModuleProxyReturn(scopeStrategy, relative(ctx.config.root, id)); + const code = `export default new Proxy(Object.create(null), { + get(_, style) { + return ${proxyReturn}; + }, + })`; + return { code }; + } + return { code: 'export default ""' }; + } + } + ]; +} + +function CoverageTransform(ctx) { + return { + name: "vitest:coverage-transform", + transform(srcCode, id) { + var _a, _b; + return (_b = (_a = ctx.coverageProvider) == null ? void 0 : _a.onFileTransform) == null ? void 0 : _b.call(_a, srcCode, id, this); + } + }; +} + +async function VitestPlugin(options = {}, ctx = new Vitest("test")) { + const getRoot = () => { + var _a; + return ((_a = ctx.config) == null ? void 0 : _a.root) || options.root || process.cwd(); + }; + async function UIPlugin() { + await ensurePackageInstalled("@vitest/ui", getRoot()); + return (await import('@vitest/ui')).default(options.uiBase); + } + async function BrowserPlugin() { + await ensurePackageInstalled("@vitest/browser", getRoot()); + return (await import('@vitest/browser')).default("/"); + } + return [ + { + name: "vitest", + enforce: "pre", + options() { + this.meta.watchMode = false; + }, + config(viteConfig) { + var _a, _b, _c; + const preOptions = deepMerge( + {}, + configDefaults, + options, + removeUndefinedValues(viteConfig.test ?? {}) + ); + preOptions.api = resolveApiConfig(preOptions); + if (viteConfig.define) { + delete viteConfig.define["import.meta.vitest"]; + delete viteConfig.define["process.env"]; + } + const defines = {}; + for (const key in viteConfig.define) { + const val = viteConfig.define[key]; + let replacement; + try { + replacement = typeof val === "string" ? JSON.parse(val) : val; + } catch { + continue; + } + if (key.startsWith("import.meta.env.")) { + const envKey = key.slice("import.meta.env.".length); + process.env[envKey] = replacement; + delete viteConfig.define[key]; + } else if (key.startsWith("process.env.")) { + const envKey = key.slice("process.env.".length); + process.env[envKey] = replacement; + delete viteConfig.define[key]; + } else if (!key.includes(".")) { + defines[key] = replacement; + delete viteConfig.define[key]; + } + } + options.defines = defines; + let open; + if (preOptions.ui && preOptions.open) + open = preOptions.uiBase ?? "/__vitest__/"; + else if (preOptions.browser) + open = "/"; + const config = { + esbuild: { + sourcemap: "external", + legalComments: "inline" + }, + resolve: { + mainFields: [], + alias: preOptions.alias, + conditions: ["node"], + browserField: false + }, + server: { + ...preOptions.api, + watch: { + ignored: preOptions.watchExclude + }, + open, + hmr: false, + preTransformRequests: false + } + }; + const classNameStrategy = preOptions.css && ((_b = (_a = preOptions.css) == null ? void 0 : _a.modules) == null ? void 0 : _b.classNameStrategy); + if (classNameStrategy !== "scoped") { + config.css ?? (config.css = {}); + (_c = config.css).modules ?? (_c.modules = {}); + config.css.modules.generateScopedName = (name, filename) => { + const root = getRoot(); + return generateScopedClassName(classNameStrategy, name, relative(root, filename)); + }; + } + if (!options.browser) { + Object.assign(config, { + cacheDir: void 0, + optimizeDeps: { + disabled: true, + entries: [] + } + }); + } + return config; + }, + async configResolved(viteConfig) { + var _a, _b, _c, _d; + const viteConfigTest = viteConfig.test || {}; + if (viteConfigTest.watch === false) + viteConfigTest.run = true; + if ("alias" in viteConfigTest) + delete viteConfigTest.alias; + options = deepMerge( + {}, + configDefaults, + viteConfigTest, + options + ); + options.api = resolveApiConfig(options); + const { PROD, DEV, ...envs } = viteConfig.env; + (_a = process.env).PROD ?? (_a.PROD = PROD ? "1" : ""); + (_b = process.env).DEV ?? (_b.DEV = DEV ? "1" : ""); + (_c = process.env).SSR ?? (_c.SSR = "1"); + for (const name in envs) + (_d = process.env)[name] ?? (_d[name] = envs[name]); + }, + async configureServer(server) { + try { + await ctx.setServer(options, server); + if (options.api && options.watch) + (await import('./chunk-api-setup.16ac28c0.js')).setup(ctx); + } catch (err) { + ctx.logger.printError(err, true); + process.exit(1); + } + if (!options.watch) + await server.watcher.close(); + } + }, + EnvReplacerPlugin(), + MocksPlugin(), + GlobalSetupPlugin(ctx), + ...options.browser ? await BrowserPlugin() : [], + ...CSSEnablerPlugin(ctx), + CoverageTransform(ctx), + options.ui ? await UIPlugin() : null + ].filter(notNullish); +} + +async function createVitest(mode, options, viteOverrides = {}) { + var _a; + const ctx = new Vitest(mode); + const root = resolve(options.root || process.cwd()); + const configPath = options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root }); + const config = { + logLevel: "error", + configFile: configPath, + mode: options.mode || process.env.NODE_ENV || mode, + plugins: await VitestPlugin(options, ctx) + }; + const server = await createServer(mergeConfig(config, mergeConfig(viteOverrides, { root: options.root }))); + if ((_a = ctx.config.api) == null ? void 0 : _a.port) + await server.listen(); + else + await server.pluginContainer.buildStart({}); + return ctx; +} + +const keys = [ + ["a", "rerun all tests"], + ["f", "rerun only failed tests"], + ["u", "update snapshot"], + ["p", "filter by a filename"], + ["t", "filter by a test name regex pattern"], + ["q", "quit"] +]; +function printShortcutsHelp() { + stdout().write( + ` +${c.bold(" Watch Usage")} +${keys.map((i) => c.dim(" press ") + c.reset(c.bold(i[0])) + c.dim(` to ${i[1]}`)).join("\n")} +` + ); +} +function registerConsoleShortcuts(ctx) { + let latestFilename = ""; + async function _keypressHandler(str, key) { + if (str === "" || str === "\x1B" || key && key.ctrl && key.name === "c") + return ctx.exit(true); + if (!isWindows && key && key.ctrl && key.name === "z") { + process.kill(process.ppid, "SIGTSTP"); + process.kill(process.pid, "SIGTSTP"); + return; + } + if (ctx.runningPromise) + return; + const name = key == null ? void 0 : key.name; + if (name === "q") + return ctx.exit(true); + if (ctx.mode === "typecheck") + return; + if (name === "h") + return printShortcutsHelp(); + if (name === "u") + return ctx.updateSnapshot(); + if (name === "a" || name === "return") + return ctx.changeNamePattern(""); + if (name === "f") + return ctx.rerunFailed(); + if (name === "t") + return inputNamePattern(); + if (name === "p") + return inputFilePattern(); + } + async function keypressHandler(str, key) { + await _keypressHandler(str, key); + } + async function inputNamePattern() { + var _a; + off(); + const { filter = "" } = await prompts([{ + name: "filter", + type: "text", + message: "Input test name pattern (RegExp)", + initial: ((_a = ctx.config.testNamePattern) == null ? void 0 : _a.source) || "" + }]); + await ctx.changeNamePattern(filter, void 0, "change pattern"); + on(); + } + async function inputFilePattern() { + off(); + const { filter = "" } = await prompts([{ + name: "filter", + type: "text", + message: "Input filename pattern", + initial: latestFilename + }]); + latestFilename = filter; + await ctx.changeFilenamePattern(filter); + on(); + } + let rl; + function on() { + off(); + rl = require$$0$3.createInterface({ input: process.stdin, escapeCodeTimeout: 50 }); + require$$0$3.emitKeypressEvents(process.stdin, rl); + if (process.stdin.isTTY) + process.stdin.setRawMode(true); + process.stdin.on("keypress", keypressHandler); + } + function off() { + rl == null ? void 0 : rl.close(); + rl = void 0; + process.stdin.removeListener("keypress", keypressHandler); + if (process.stdin.isTTY) + process.stdin.setRawMode(false); + } + on(); +} + +async function startVitest(mode, cliFilters, options, viteOverrides) { + var _a; + process.env.TEST = "true"; + process.env.VITEST = "true"; + (_a = process.env).NODE_ENV ?? (_a.NODE_ENV = options.mode || "test"); + if (options.run) + options.watch = false; + if (options.browser) + options.threads = false; + const root = resolve(options.root || process.cwd()); + if (!await ensurePackageInstalled("vite", root)) { + process.exitCode = 1; + return; + } + if (typeof options.coverage === "boolean") + options.coverage = { enabled: options.coverage }; + const ctx = await createVitest(mode, options, viteOverrides); + if (mode === "test" && ctx.config.coverage.enabled) { + const provider = ctx.config.coverage.provider || "c8"; + if (typeof provider === "string") { + const requiredPackages = CoverageProviderMap[provider]; + if (!await ensurePackageInstalled(requiredPackages, root)) { + process.exitCode = 1; + return ctx; + } + } + } + const environmentPackage = getEnvPackageName(ctx.config.environment); + if (environmentPackage && !await ensurePackageInstalled(environmentPackage, root)) { + process.exitCode = 1; + return ctx; + } + if (process.stdin.isTTY && ctx.config.watch) + registerConsoleShortcuts(ctx); + ctx.onServerRestart((reason) => { + ctx.report("onServerRestart", reason); + if (process.env.VITEST_CLI_WRAPPER) + process.exit(EXIT_CODE_RESTART); + }); + ctx.onAfterSetServer(() => { + ctx.start(cliFilters); + }); + try { + await ctx.start(cliFilters); + } catch (e) { + process.exitCode = 1; + await ctx.logger.printError(e, true, "Unhandled Error"); + ctx.logger.error("\n\n"); + return ctx; + } + if (ctx.config.watch) + return ctx; + await ctx.close(); + return ctx; +} + +export { BaseSequencer as B, VitestPlugin as V, createVitest as c, divider as d, startVitest as s, version$1 as v }; diff --git a/node_modules/vitest/dist/chunk-utils-env.b861e3a0.js b/node_modules/vitest/dist/chunk-utils-env.b861e3a0.js new file mode 100644 index 0000000..01a104e --- /dev/null +++ b/node_modules/vitest/dist/chunk-utils-env.b861e3a0.js @@ -0,0 +1,228 @@ +import url from 'node:url'; +import g from 'path'; + +function normalizeWindowsPath(input = "") { + if (!input.includes("\\")) { + return input; + } + return input.replace(/\\/g, "/"); +} + +const _UNC_REGEX = /^[/][/]/; +const _UNC_DRIVE_REGEX = /^[/][/]([.]{1,2}[/])?([a-zA-Z]):[/]/; +const _IS_ABSOLUTE_RE = /^\/|^\\|^[a-zA-Z]:[/\\]/; +const sep = "/"; +const delimiter = ":"; +const normalize = function(path2) { + if (path2.length === 0) { + return "."; + } + path2 = normalizeWindowsPath(path2); + const isUNCPath = path2.match(_UNC_REGEX); + const hasUNCDrive = isUNCPath && path2.match(_UNC_DRIVE_REGEX); + const isPathAbsolute = isAbsolute(path2); + const trailingSeparator = path2[path2.length - 1] === "/"; + path2 = normalizeString(path2, !isPathAbsolute); + if (path2.length === 0) { + if (isPathAbsolute) { + return "/"; + } + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) { + path2 += "/"; + } + if (isUNCPath) { + if (hasUNCDrive) { + return `//./${path2}`; + } + return `//${path2}`; + } + return isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2; +}; +const join = function(...args) { + if (args.length === 0) { + return "."; + } + let joined; + for (let i = 0; i < args.length; ++i) { + const arg = args[i]; + if (arg.length > 0) { + if (joined === void 0) { + joined = arg; + } else { + joined += `/${arg}`; + } + } + } + if (joined === void 0) { + return "."; + } + return normalize(joined); +}; +const resolve = function(...args) { + args = args.map((arg) => normalizeWindowsPath(arg)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + const path2 = i >= 0 ? args[i] : process.cwd(); + if (path2.length === 0) { + continue; + } + resolvedPath = `${path2}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path2); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path2, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let i = 0; i <= path2.length; ++i) { + if (i < path2.length) { + char = path2[i]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === i - 1 || dots === 1) ; else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = i; + dots = 0; + continue; + } else if (res.length !== 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path2.slice(lastSlash + 1, i)}`; + } else { + res = path2.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; +const toNamespacedPath = function(p) { + return normalizeWindowsPath(p); +}; +const extname = function(p) { + return g.posix.extname(normalizeWindowsPath(p)); +}; +const relative = function(from, to) { + return g.posix.relative(normalizeWindowsPath(from), normalizeWindowsPath(to)); +}; +const dirname = function(p) { + return g.posix.dirname(normalizeWindowsPath(p)); +}; +const format = function(p) { + return normalizeWindowsPath(g.posix.format(p)); +}; +const basename = function(p, ext) { + return g.posix.basename(normalizeWindowsPath(p), ext); +}; +const parse = function(p) { + return g.posix.parse(normalizeWindowsPath(p)); +}; + +const _path = /*#__PURE__*/Object.freeze({ + __proto__: null, + sep: sep, + delimiter: delimiter, + normalize: normalize, + join: join, + resolve: resolve, + normalizeString: normalizeString, + isAbsolute: isAbsolute, + toNamespacedPath: toNamespacedPath, + extname: extname, + relative: relative, + dirname: dirname, + format: format, + basename: basename, + parse: parse +}); + +({ + ..._path +}); + +var _a; +const isNode = typeof process < "u" && typeof process.stdout < "u" && !((_a = process.versions) == null ? void 0 : _a.deno) && !globalThis.window; +const isBrowser = typeof window !== "undefined"; + +const rootDir = isNode ? resolve(url.fileURLToPath(import.meta.url), "../../") : import.meta.url; +const distDir = isNode ? resolve(url.fileURLToPath(import.meta.url), "../../dist") : import.meta.url; +const defaultPort = 51204; +const EXIT_CODE_RESTART = 43; +const API_PATH = "/__vitest_api__"; +const configFiles = [ + "vitest.config.ts", + "vitest.config.mts", + "vitest.config.cts", + "vitest.config.js", + "vitest.config.mjs", + "vitest.config.cjs", + "vite.config.ts", + "vite.config.mts", + "vite.config.cts", + "vite.config.js", + "vite.config.mjs", + "vite.config.cjs" +]; +const globalApis = [ + "suite", + "test", + "describe", + "it", + "chai", + "expect", + "assert", + "expectTypeOf", + "assertType", + "vitest", + "vi", + "beforeAll", + "afterAll", + "beforeEach", + "afterEach" +]; + +export { API_PATH as A, EXIT_CODE_RESTART as E, isBrowser as a, resolve as b, basename as c, dirname as d, extname as e, distDir as f, rootDir as g, isAbsolute as h, isNode as i, join as j, configFiles as k, defaultPort as l, globalApis as m, normalize as n, relative as r, toNamespacedPath as t }; diff --git a/node_modules/vitest/dist/chunk-utils-import.2baa69a9.js b/node_modules/vitest/dist/chunk-utils-import.2baa69a9.js new file mode 100644 index 0000000..a9b2128 --- /dev/null +++ b/node_modules/vitest/dist/chunk-utils-import.2baa69a9.js @@ -0,0 +1,3041 @@ +import { g as getCurrentSuite, w as withTimeout, a as getDefaultHookTimeout, s as suite, t as test, d as describe, i as it, b as bench, c as createExpect, e as globalExpect } from './chunk-runtime-chain.6df5a66b.js'; +import { g as getWorkerState, R as RealDate, r as resetDate, m as mockDate, a as resetModules } from './chunk-mock-date.a1c85759.js'; +import { p as parseSingleStack } from './chunk-utils-source-map.60562959.js'; +import { c as commonjsGlobal } from './vendor-_commonjsHelpers.addc3445.js'; +import util from 'util'; +import { s as spyOn, f as fn, i as isMockFunction, a as spies } from './vendor-index.723a074f.js'; +import { s as safeSetTimeout } from './chunk-utils-timers.52534f96.js'; +import * as chai from 'chai'; +import { assert, should } from 'chai'; + +function waitNextTick() { + return new Promise((resolve) => safeSetTimeout(resolve, 0)); +} +async function waitForImportsToResolve() { + await waitNextTick(); + const state = getWorkerState(); + const promises = []; + let resolvingCount = 0; + for (const mod of state.moduleCache.values()) { + if (mod.promise && !mod.evaluated) + promises.push(mod.promise); + if (mod.resolving) + resolvingCount++; + } + if (!promises.length && !resolvingCount) + return; + await Promise.allSettled(promises); + await waitForImportsToResolve(); +} + +let _test; +function setCurrentTest(test) { + _test = test; +} +function getCurrentTest() { + return _test; +} + +const beforeAll = (fn, timeout) => getCurrentSuite().on("beforeAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true)); +const afterAll = (fn, timeout) => getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true)); +const beforeEach = (fn, timeout) => getCurrentSuite().on("beforeEach", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true)); +const afterEach = (fn, timeout) => getCurrentSuite().on("afterEach", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true)); +const onTestFailed = createTestHook("onTestFailed", (test, handler) => { + test.onFailed || (test.onFailed = []); + test.onFailed.push(handler); +}); +function createTestHook(name, handler) { + return (fn) => { + const current = getCurrentTest(); + if (!current) + throw new Error(`Hook ${name}() can only be called inside a test`); + handler(current, fn); + }; +} + +function withCallback(fn) { + return new Promise( + (resolve, reject) => fn((err) => { + if (err) + reject(err); + else + resolve(); + }) + ); +} + +const filesCount = /* @__PURE__ */ new Map(); +const cache = /* @__PURE__ */ new Map(); +function runOnce(fn, key) { + const filepath = getWorkerState().filepath || "__unknown_files__"; + if (!key) { + filesCount.set(filepath, (filesCount.get(filepath) || 0) + 1); + key = String(filesCount.get(filepath)); + } + const id = `${filepath}:${key}`; + if (!cache.has(id)) + cache.set(id, fn()); + return cache.get(id); +} +function isFirstRun() { + let firstRun = false; + runOnce(() => { + firstRun = true; + }, "__vitest_first_run__"); + return firstRun; +} +function resetRunOnceCounter() { + filesCount.clear(); +} + +function createSimpleStackTrace(options) { + const { message = "error", stackTraceLimit = 1 } = options || {}; + const limit = Error.stackTraceLimit; + const prepareStackTrace = Error.prepareStackTrace; + Error.stackTraceLimit = stackTraceLimit; + Error.prepareStackTrace = (e) => e.stack; + const err = new Error(message); + const stackTrace = err.stack || ""; + Error.prepareStackTrace = prepareStackTrace; + Error.stackTraceLimit = limit; + return stackTrace; +} + +/** + * A reference to the global object + * + * @type {object} globalObject + */ +var globalObject$1; + +/* istanbul ignore else */ +if (typeof commonjsGlobal !== "undefined") { + // Node + globalObject$1 = commonjsGlobal; +} else if (typeof window !== "undefined") { + // Browser + globalObject$1 = window; +} else { + // WebWorker + globalObject$1 = self; +} + +var global = globalObject$1; + +/** + * Is true when the environment causes an error to be thrown for accessing the + * __proto__ property. + * + * This is necessary in order to support `node --disable-proto=throw`. + * + * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto + * + * @type {boolean} + */ +let throwsOnProto$1; +try { + const object = {}; + // eslint-disable-next-line no-proto, no-unused-expressions + object.__proto__; + throwsOnProto$1 = false; +} catch (_) { + // This branch is covered when tests are run with `--disable-proto=throw`, + // however we can test both branches at the same time, so this is ignored + /* istanbul ignore next */ + throwsOnProto$1 = true; +} + +var throwsOnProto_1 = throwsOnProto$1; + +var call = Function.call; +var throwsOnProto = throwsOnProto_1; + +var disallowedProperties = [ + // ignore size because it throws from Map + "size", + "caller", + "callee", + "arguments", +]; + +// This branch is covered when tests are run with `--disable-proto=throw`, +// however we can test both branches at the same time, so this is ignored +/* istanbul ignore next */ +if (throwsOnProto) { + disallowedProperties.push("__proto__"); +} + +var copyPrototypeMethods = function copyPrototypeMethods(prototype) { + // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods + return Object.getOwnPropertyNames(prototype).reduce(function ( + result, + name + ) { + if (disallowedProperties.includes(name)) { + return result; + } + + if (typeof prototype[name] !== "function") { + return result; + } + + result[name] = call.bind(prototype[name]); + + return result; + }, + Object.create(null)); +}; + +var copyPrototype$5 = copyPrototypeMethods; + +var array = copyPrototype$5(Array.prototype); + +var every$1 = array.every; + +/** + * @private + */ +function hasCallsLeft(callMap, spy) { + if (callMap[spy.id] === undefined) { + callMap[spy.id] = 0; + } + + return callMap[spy.id] < spy.callCount; +} + +/** + * @private + */ +function checkAdjacentCalls(callMap, spy, index, spies) { + var calledBeforeNext = true; + + if (index !== spies.length - 1) { + calledBeforeNext = spy.calledBefore(spies[index + 1]); + } + + if (hasCallsLeft(callMap, spy) && calledBeforeNext) { + callMap[spy.id] += 1; + return true; + } + + return false; +} + +/** + * A Sinon proxy object (fake, spy, stub) + * + * @typedef {object} SinonProxy + * @property {Function} calledBefore - A method that determines if this proxy was called before another one + * @property {string} id - Some id + * @property {number} callCount - Number of times this proxy has been called + */ + +/** + * Returns true when the spies have been called in the order they were supplied in + * + * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments + * @returns {boolean} true when spies are called in order, false otherwise + */ +function calledInOrder(spies) { + var callMap = {}; + // eslint-disable-next-line no-underscore-dangle + var _spies = arguments.length > 1 ? arguments : spies; + + return every$1(_spies, checkAdjacentCalls.bind(null, callMap)); +} + +var calledInOrder_1 = calledInOrder; + +/** + * Returns a display name for a function + * + * @param {Function} func + * @returns {string} + */ +var functionName$1 = function functionName(func) { + if (!func) { + return ""; + } + + try { + return ( + func.displayName || + func.name || + // Use function decomposition as a last resort to get function + // name. Does not rely on function decomposition to work - if it + // doesn't debugging will be slightly less informative + // (i.e. toString will say 'spy' rather than 'myFunc'). + (String(func).match(/function ([^\s(]+)/) || [])[1] + ); + } catch (e) { + // Stringify may fail and we might get an exception, as a last-last + // resort fall back to empty string. + return ""; + } +}; + +var functionName = functionName$1; + +/** + * Returns a display name for a value from a constructor + * + * @param {object} value A value to examine + * @returns {(string|null)} A string or null + */ +function className(value) { + return ( + (value.constructor && value.constructor.name) || + // The next branch is for IE11 support only: + // Because the name property is not set on the prototype + // of the Function object, we finally try to grab the + // name from its definition. This will never be reached + // in node, so we are not able to test this properly. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name + (typeof value.constructor === "function" && + /* istanbul ignore next */ + functionName(value.constructor)) || + null + ); +} + +var className_1 = className; + +var deprecated = {}; + +/* eslint-disable no-console */ + +(function (exports) { + + /** + * Returns a function that will invoke the supplied function and print a + * deprecation warning to the console each time it is called. + * + * @param {Function} func + * @param {string} msg + * @returns {Function} + */ + exports.wrap = function (func, msg) { + var wrapped = function () { + exports.printWarning(msg); + return func.apply(this, arguments); + }; + if (func.prototype) { + wrapped.prototype = func.prototype; + } + return wrapped; + }; + + /** + * Returns a string which can be supplied to `wrap()` to notify the user that a + * particular part of the sinon API has been deprecated. + * + * @param {string} packageName + * @param {string} funcName + * @returns {string} + */ + exports.defaultMsg = function (packageName, funcName) { + return `${packageName}.${funcName} is deprecated and will be removed from the public API in a future version of ${packageName}.`; + }; + + /** + * Prints a warning on the console, when it exists + * + * @param {string} msg + * @returns {undefined} + */ + exports.printWarning = function (msg) { + /* istanbul ignore next */ + if (typeof process === "object" && process.emitWarning) { + // Emit Warnings in Node + process.emitWarning(msg); + } else if (console.info) { + console.info(msg); + } else { + console.log(msg); + } + }; +} (deprecated)); + +/** + * Returns true when fn returns true for all members of obj. + * This is an every implementation that works for all iterables + * + * @param {object} obj + * @param {Function} fn + * @returns {boolean} + */ +var every = function every(obj, fn) { + var pass = true; + + try { + // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods + obj.forEach(function () { + if (!fn.apply(this, arguments)) { + // Throwing an error is the only way to break `forEach` + throw new Error(); + } + }); + } catch (e) { + pass = false; + } + + return pass; +}; + +var sort = array.sort; +var slice = array.slice; + +/** + * @private + */ +function comparator(a, b) { + // uuid, won't ever be equal + var aCall = a.getCall(0); + var bCall = b.getCall(0); + var aId = (aCall && aCall.callId) || -1; + var bId = (bCall && bCall.callId) || -1; + + return aId < bId ? -1 : 1; +} + +/** + * A Sinon proxy object (fake, spy, stub) + * + * @typedef {object} SinonProxy + * @property {Function} getCall - A method that can return the first call + */ + +/** + * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call + * + * @param {SinonProxy[] | SinonProxy} spies + * @returns {SinonProxy[]} + */ +function orderByFirstCall(spies) { + return sort(slice(spies), comparator); +} + +var orderByFirstCall_1 = orderByFirstCall; + +var copyPrototype$4 = copyPrototypeMethods; + +var _function = copyPrototype$4(Function.prototype); + +var copyPrototype$3 = copyPrototypeMethods; + +var map = copyPrototype$3(Map.prototype); + +var copyPrototype$2 = copyPrototypeMethods; + +var object = copyPrototype$2(Object.prototype); + +var copyPrototype$1 = copyPrototypeMethods; + +var set = copyPrototype$1(Set.prototype); + +var copyPrototype = copyPrototypeMethods; + +var string = copyPrototype(String.prototype); + +var prototypes = { + array: array, + function: _function, + map: map, + object: object, + set: set, + string: string, +}; + +var typeDetect = {exports: {}}; + +(function (module, exports) { + (function (global, factory) { + module.exports = factory() ; + }(commonjsGlobal, (function () { + /* ! + * type-detect + * Copyright(c) 2013 jake luer + * MIT Licensed + */ + var promiseExists = typeof Promise === 'function'; + + /* eslint-disable no-undef */ + var globalObject = typeof self === 'object' ? self : commonjsGlobal; // eslint-disable-line id-blacklist + + var symbolExists = typeof Symbol !== 'undefined'; + var mapExists = typeof Map !== 'undefined'; + var setExists = typeof Set !== 'undefined'; + var weakMapExists = typeof WeakMap !== 'undefined'; + var weakSetExists = typeof WeakSet !== 'undefined'; + var dataViewExists = typeof DataView !== 'undefined'; + var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined'; + var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined'; + var setEntriesExists = setExists && typeof Set.prototype.entries === 'function'; + var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function'; + var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries()); + var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries()); + var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function'; + var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]()); + var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function'; + var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]()); + var toStringLeftSliceLength = 8; + var toStringRightSliceLength = -1; + /** + * ### typeOf (obj) + * + * Uses `Object.prototype.toString` to determine the type of an object, + * normalising behaviour across engine versions & well optimised. + * + * @param {Mixed} object + * @return {String} object type + * @api public + */ + function typeDetect(obj) { + /* ! Speed optimisation + * Pre: + * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled) + * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled) + * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled) + * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled) + * function x 2,556,769 ops/sec ±1.73% (77 runs sampled) + * Post: + * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled) + * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled) + * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled) + * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled) + * function x 31,296,870 ops/sec ±0.96% (83 runs sampled) + */ + var typeofObj = typeof obj; + if (typeofObj !== 'object') { + return typeofObj; + } + + /* ! Speed optimisation + * Pre: + * null x 28,645,765 ops/sec ±1.17% (82 runs sampled) + * Post: + * null x 36,428,962 ops/sec ±1.37% (84 runs sampled) + */ + if (obj === null) { + return 'null'; + } + + /* ! Spec Conformance + * Test: `Object.prototype.toString.call(window)`` + * - Node === "[object global]" + * - Chrome === "[object global]" + * - Firefox === "[object Window]" + * - PhantomJS === "[object Window]" + * - Safari === "[object Window]" + * - IE 11 === "[object Window]" + * - IE Edge === "[object Window]" + * Test: `Object.prototype.toString.call(this)`` + * - Chrome Worker === "[object global]" + * - Firefox Worker === "[object DedicatedWorkerGlobalScope]" + * - Safari Worker === "[object DedicatedWorkerGlobalScope]" + * - IE 11 Worker === "[object WorkerGlobalScope]" + * - IE Edge Worker === "[object WorkerGlobalScope]" + */ + if (obj === globalObject) { + return 'global'; + } + + /* ! Speed optimisation + * Pre: + * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled) + * Post: + * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled) + */ + if ( + Array.isArray(obj) && + (symbolToStringTagExists === false || !(Symbol.toStringTag in obj)) + ) { + return 'Array'; + } + + // Not caching existence of `window` and related properties due to potential + // for `window` to be unset before tests in quasi-browser environments. + if (typeof window === 'object' && window !== null) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/browsers.html#location) + * WhatWG HTML$7.7.3 - The `Location` interface + * Test: `Object.prototype.toString.call(window.location)`` + * - IE <=11 === "[object Object]" + * - IE Edge <=13 === "[object Object]" + */ + if (typeof window.location === 'object' && obj === window.location) { + return 'Location'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#document) + * WhatWG HTML$3.1.1 - The `Document` object + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * WhatWG HTML states: + * > For historical reasons, Window objects must also have a + * > writable, configurable, non-enumerable property named + * > HTMLDocument whose value is the Document interface object. + * Test: `Object.prototype.toString.call(document)`` + * - Chrome === "[object HTMLDocument]" + * - Firefox === "[object HTMLDocument]" + * - Safari === "[object HTMLDocument]" + * - IE <=10 === "[object Document]" + * - IE 11 === "[object HTMLDocument]" + * - IE Edge <=13 === "[object HTMLDocument]" + */ + if (typeof window.document === 'object' && obj === window.document) { + return 'Document'; + } + + if (typeof window.navigator === 'object') { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray + * Test: `Object.prototype.toString.call(navigator.mimeTypes)`` + * - IE <=10 === "[object MSMimeTypesCollection]" + */ + if (typeof window.navigator.mimeTypes === 'object' && + obj === window.navigator.mimeTypes) { + return 'MimeTypeArray'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray + * Test: `Object.prototype.toString.call(navigator.plugins)`` + * - IE <=10 === "[object MSPluginsCollection]" + */ + if (typeof window.navigator.plugins === 'object' && + obj === window.navigator.plugins) { + return 'PluginArray'; + } + } + + if ((typeof window.HTMLElement === 'function' || + typeof window.HTMLElement === 'object') && + obj instanceof window.HTMLElement) { + /* ! Spec Conformance + * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) + * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement` + * Test: `Object.prototype.toString.call(document.createElement('blockquote'))`` + * - IE <=10 === "[object HTMLBlockElement]" + */ + if (obj.tagName === 'BLOCKQUOTE') { + return 'HTMLQuoteElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltabledatacellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('td')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TD') { + return 'HTMLTableDataCellElement'; + } + + /* ! Spec Conformance + * (https://html.spec.whatwg.org/#htmltableheadercellelement) + * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement` + * Note: Most browsers currently adher to the W3C DOM Level 2 spec + * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) + * which suggests that browsers should use HTMLTableCellElement for + * both TD and TH elements. WhatWG separates these. + * Test: Object.prototype.toString.call(document.createElement('th')) + * - Chrome === "[object HTMLTableCellElement]" + * - Firefox === "[object HTMLTableCellElement]" + * - Safari === "[object HTMLTableCellElement]" + */ + if (obj.tagName === 'TH') { + return 'HTMLTableHeaderCellElement'; + } + } + } + + /* ! Speed optimisation + * Pre: + * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled) + * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled) + * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled) + * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled) + * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled) + * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled) + * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled) + * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled) + * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled) + * Post: + * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled) + * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled) + * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled) + * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled) + * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled) + * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled) + * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled) + * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled) + * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled) + */ + var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]); + if (typeof stringTag === 'string') { + return stringTag; + } + + var objPrototype = Object.getPrototypeOf(obj); + /* ! Speed optimisation + * Pre: + * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled) + * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled) + * Post: + * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled) + * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled) + */ + if (objPrototype === RegExp.prototype) { + return 'RegExp'; + } + + /* ! Speed optimisation + * Pre: + * date x 2,130,074 ops/sec ±4.42% (68 runs sampled) + * Post: + * date x 3,953,779 ops/sec ±1.35% (77 runs sampled) + */ + if (objPrototype === Date.prototype) { + return 'Date'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag) + * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise": + * Test: `Object.prototype.toString.call(Promise.resolve())`` + * - Chrome <=47 === "[object Object]" + * - Edge <=20 === "[object Object]" + * - Firefox 29-Latest === "[object Promise]" + * - Safari 7.1-Latest === "[object Promise]" + */ + if (promiseExists && objPrototype === Promise.prototype) { + return 'Promise'; + } + + /* ! Speed optimisation + * Pre: + * set x 2,222,186 ops/sec ±1.31% (82 runs sampled) + * Post: + * set x 4,545,879 ops/sec ±1.13% (83 runs sampled) + */ + if (setExists && objPrototype === Set.prototype) { + return 'Set'; + } + + /* ! Speed optimisation + * Pre: + * map x 2,396,842 ops/sec ±1.59% (81 runs sampled) + * Post: + * map x 4,183,945 ops/sec ±6.59% (82 runs sampled) + */ + if (mapExists && objPrototype === Map.prototype) { + return 'Map'; + } + + /* ! Speed optimisation + * Pre: + * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled) + * Post: + * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled) + */ + if (weakSetExists && objPrototype === WeakSet.prototype) { + return 'WeakSet'; + } + + /* ! Speed optimisation + * Pre: + * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled) + * Post: + * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled) + */ + if (weakMapExists && objPrototype === WeakMap.prototype) { + return 'WeakMap'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag) + * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView": + * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))`` + * - Edge <=13 === "[object Object]" + */ + if (dataViewExists && objPrototype === DataView.prototype) { + return 'DataView'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag) + * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator": + * Test: `Object.prototype.toString.call(new Map().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (mapExists && objPrototype === mapIteratorPrototype) { + return 'Map Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag) + * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator": + * Test: `Object.prototype.toString.call(new Set().entries())`` + * - Edge <=13 === "[object Object]" + */ + if (setExists && objPrototype === setIteratorPrototype) { + return 'Set Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag) + * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator": + * Test: `Object.prototype.toString.call([][Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) { + return 'Array Iterator'; + } + + /* ! Spec Conformance + * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag) + * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator": + * Test: `Object.prototype.toString.call(''[Symbol.iterator]())`` + * - Edge <=13 === "[object Object]" + */ + if (stringIteratorExists && objPrototype === stringIteratorPrototype) { + return 'String Iterator'; + } + + /* ! Speed optimisation + * Pre: + * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled) + * Post: + * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled) + */ + if (objPrototype === null) { + return 'Object'; + } + + return Object + .prototype + .toString + .call(obj) + .slice(toStringLeftSliceLength, toStringRightSliceLength); + } + + return typeDetect; + + }))); +} (typeDetect)); + +var type = typeDetect.exports; + +/** + * Returns the lower-case result of running type from type-detect on the value + * + * @param {*} value + * @returns {string} + */ +var typeOf = function typeOf(value) { + return type(value).toLowerCase(); +}; + +/** + * Returns a string representation of the value + * + * @param {*} value + * @returns {string} + */ +function valueToString(value) { + if (value && value.toString) { + // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods + return value.toString(); + } + return String(value); +} + +var valueToString_1 = valueToString; + +var lib = { + global: global, + calledInOrder: calledInOrder_1, + className: className_1, + deprecated: deprecated, + every: every, + functionName: functionName$1, + orderByFirstCall: orderByFirstCall_1, + prototypes: prototypes, + typeOf: typeOf, + valueToString: valueToString_1, +}; + +const globalObject = lib.global; + +/** + * @typedef {object} IdleDeadline + * @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout + * @property {function():number} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period + */ + +/** + * Queues a function to be called during a browser's idle periods + * + * @callback RequestIdleCallback + * @param {function(IdleDeadline)} callback + * @param {{timeout: number}} options - an options object + * @returns {number} the id + */ + +/** + * @callback NextTick + * @param {VoidVarArgsFunc} callback - the callback to run + * @param {...*} arguments - optional arguments to call the callback with + * @returns {void} + */ + +/** + * @callback SetImmediate + * @param {VoidVarArgsFunc} callback - the callback to run + * @param {...*} arguments - optional arguments to call the callback with + * @returns {NodeImmediate} + */ + +/** + * @callback VoidVarArgsFunc + * @param {...*} callback - the callback to run + * @returns {void} + */ + +/** + * @typedef RequestAnimationFrame + * @property {function(number):void} requestAnimationFrame + * @returns {number} - the id + */ + +/** + * @typedef Performance + * @property {function(): number} now + */ + +/* eslint-disable jsdoc/require-property-description */ +/** + * @typedef {object} Clock + * @property {number} now - the current time + * @property {Date} Date - the Date constructor + * @property {number} loopLimit - the maximum number of timers before assuming an infinite loop + * @property {RequestIdleCallback} requestIdleCallback + * @property {function(number):void} cancelIdleCallback + * @property {setTimeout} setTimeout + * @property {clearTimeout} clearTimeout + * @property {NextTick} nextTick + * @property {queueMicrotask} queueMicrotask + * @property {setInterval} setInterval + * @property {clearInterval} clearInterval + * @property {SetImmediate} setImmediate + * @property {function(NodeImmediate):void} clearImmediate + * @property {function():number} countTimers + * @property {RequestAnimationFrame} requestAnimationFrame + * @property {function(number):void} cancelAnimationFrame + * @property {function():void} runMicrotasks + * @property {function(string | number): number} tick + * @property {function(string | number): Promise} tickAsync + * @property {function(): number} next + * @property {function(): Promise} nextAsync + * @property {function(): number} runAll + * @property {function(): number} runToFrame + * @property {function(): Promise} runAllAsync + * @property {function(): number} runToLast + * @property {function(): Promise} runToLastAsync + * @property {function(): void} reset + * @property {function(number | Date): void} setSystemTime + * @property {Performance} performance + * @property {function(number[]): number[]} hrtime - process.hrtime (legacy) + * @property {function(): void} uninstall Uninstall the clock. + * @property {Function[]} methods - the methods that are faked + * @property {boolean} [shouldClearNativeTimers] inherited from config + */ +/* eslint-enable jsdoc/require-property-description */ + +/** + * Configuration object for the `install` method. + * + * @typedef {object} Config + * @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch) + * @property {string[]} [toFake] names of the methods that should be faked. + * @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll() + * @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false) + * @property {number} [advanceTimeDelta] increment mocked time every <> ms (default: 20ms) + * @property {boolean} [shouldClearNativeTimers] forwards clear timer calls to native functions if they are not fakes (default: false) + */ + +/* eslint-disable jsdoc/require-property-description */ +/** + * The internal structure to describe a scheduled fake timer + * + * @typedef {object} Timer + * @property {Function} func + * @property {*[]} args + * @property {number} delay + * @property {number} callAt + * @property {number} createdAt + * @property {boolean} immediate + * @property {number} id + * @property {Error} [error] + */ + +/** + * A Node timer + * + * @typedef {object} NodeImmediate + * @property {function(): boolean} hasRef + * @property {function(): NodeImmediate} ref + * @property {function(): NodeImmediate} unref + */ +/* eslint-enable jsdoc/require-property-description */ + +/* eslint-disable complexity */ + +/** + * Mocks available features in the specified global namespace. + * + * @param {*} _global Namespace to mock (e.g. `window`) + * @returns {FakeTimers} + */ +function withGlobal(_global) { + const userAgent = _global.navigator && _global.navigator.userAgent; + const isRunningInIE = userAgent && userAgent.indexOf("MSIE ") > -1; + const maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint + const idCounterStart = 1e12; // arbitrarily large number to avoid collisions with native timer IDs + const NOOP = function () { + return undefined; + }; + const NOOP_ARRAY = function () { + return []; + }; + const timeoutResult = _global.setTimeout(NOOP, 0); + const addTimerReturnsObject = typeof timeoutResult === "object"; + const hrtimePresent = + _global.process && typeof _global.process.hrtime === "function"; + const hrtimeBigintPresent = + hrtimePresent && typeof _global.process.hrtime.bigint === "function"; + const nextTickPresent = + _global.process && typeof _global.process.nextTick === "function"; + const utilPromisify = _global.process && util.promisify; + const performancePresent = + _global.performance && typeof _global.performance.now === "function"; + const hasPerformancePrototype = + _global.Performance && + (typeof _global.Performance).match(/^(function|object)$/); + const hasPerformanceConstructorPrototype = + _global.performance && + _global.performance.constructor && + _global.performance.constructor.prototype; + const queueMicrotaskPresent = _global.hasOwnProperty("queueMicrotask"); + const requestAnimationFramePresent = + _global.requestAnimationFrame && + typeof _global.requestAnimationFrame === "function"; + const cancelAnimationFramePresent = + _global.cancelAnimationFrame && + typeof _global.cancelAnimationFrame === "function"; + const requestIdleCallbackPresent = + _global.requestIdleCallback && + typeof _global.requestIdleCallback === "function"; + const cancelIdleCallbackPresent = + _global.cancelIdleCallback && + typeof _global.cancelIdleCallback === "function"; + const setImmediatePresent = + _global.setImmediate && typeof _global.setImmediate === "function"; + + // Make properties writable in IE, as per + // https://www.adequatelygood.com/Replacing-setTimeout-Globally.html + /* eslint-disable no-self-assign */ + if (isRunningInIE) { + _global.setTimeout = _global.setTimeout; + _global.clearTimeout = _global.clearTimeout; + _global.setInterval = _global.setInterval; + _global.clearInterval = _global.clearInterval; + _global.Date = _global.Date; + } + + // setImmediate is not a standard function + // avoid adding the prop to the window object if not present + if (setImmediatePresent) { + _global.setImmediate = _global.setImmediate; + _global.clearImmediate = _global.clearImmediate; + } + /* eslint-enable no-self-assign */ + + _global.clearTimeout(timeoutResult); + + const NativeDate = _global.Date; + let uniqueTimerId = idCounterStart; + + /** + * @param {number} num + * @returns {boolean} + */ + function isNumberFinite(num) { + if (Number.isFinite) { + return Number.isFinite(num); + } + + return isFinite(num); + } + + let isNearInfiniteLimit = false; + + /** + * @param {Clock} clock + * @param {number} i + */ + function checkIsNearInfiniteLimit(clock, i) { + if (clock.loopLimit && i === clock.loopLimit - 1) { + isNearInfiniteLimit = true; + } + } + + /** + * + */ + function resetIsNearInfiniteLimit() { + isNearInfiniteLimit = false; + } + + /** + * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into + * number of milliseconds. This is used to support human-readable strings passed + * to clock.tick() + * + * @param {string} str + * @returns {number} + */ + function parseTime(str) { + if (!str) { + return 0; + } + + const strings = str.split(":"); + const l = strings.length; + let i = l; + let ms = 0; + let parsed; + + if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { + throw new Error( + "tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits" + ); + } + + while (i--) { + parsed = parseInt(strings[i], 10); + + if (parsed >= 60) { + throw new Error(`Invalid time ${str}`); + } + + ms += parsed * Math.pow(60, l - i - 1); + } + + return ms * 1000; + } + + /** + * Get the decimal part of the millisecond value as nanoseconds + * + * @param {number} msFloat the number of milliseconds + * @returns {number} an integer number of nanoseconds in the range [0,1e6) + * + * Example: nanoRemainer(123.456789) -> 456789 + */ + function nanoRemainder(msFloat) { + const modulo = 1e6; + const remainder = (msFloat * 1e6) % modulo; + const positiveRemainder = + remainder < 0 ? remainder + modulo : remainder; + + return Math.floor(positiveRemainder); + } + + /** + * Used to grok the `now` parameter to createClock. + * + * @param {Date|number} epoch the system time + * @returns {number} + */ + function getEpoch(epoch) { + if (!epoch) { + return 0; + } + if (typeof epoch.getTime === "function") { + return epoch.getTime(); + } + if (typeof epoch === "number") { + return epoch; + } + throw new TypeError("now should be milliseconds since UNIX epoch"); + } + + /** + * @param {number} from + * @param {number} to + * @param {Timer} timer + * @returns {boolean} + */ + function inRange(from, to, timer) { + return timer && timer.callAt >= from && timer.callAt <= to; + } + + /** + * @param {Clock} clock + * @param {Timer} job + */ + function getInfiniteLoopError(clock, job) { + const infiniteLoopError = new Error( + `Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!` + ); + + if (!job.error) { + return infiniteLoopError; + } + + // pattern never matched in Node + const computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/; + let clockMethodPattern = new RegExp( + String(Object.keys(clock).join("|")) + ); + + if (addTimerReturnsObject) { + // node.js environment + clockMethodPattern = new RegExp( + `\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+` + ); + } + + let matchedLineIndex = -1; + job.error.stack.split("\n").some(function (line, i) { + // If we've matched a computed target line (e.g. setTimeout) then we + // don't need to look any further. Return true to stop iterating. + const matchedComputedTarget = line.match(computedTargetPattern); + /* istanbul ignore if */ + if (matchedComputedTarget) { + matchedLineIndex = i; + return true; + } + + // If we've matched a clock method line, then there may still be + // others further down the trace. Return false to keep iterating. + const matchedClockMethod = line.match(clockMethodPattern); + if (matchedClockMethod) { + matchedLineIndex = i; + return false; + } + + // If we haven't matched anything on this line, but we matched + // previously and set the matched line index, then we can stop. + // If we haven't matched previously, then we should keep iterating. + return matchedLineIndex >= 0; + }); + + const stack = `${infiniteLoopError}\n${job.type || "Microtask"} - ${ + job.func.name || "anonymous" + }\n${job.error.stack + .split("\n") + .slice(matchedLineIndex + 1) + .join("\n")}`; + + try { + Object.defineProperty(infiniteLoopError, "stack", { + value: stack, + }); + } catch (e) { + // noop + } + + return infiniteLoopError; + } + + /** + * @param {Date} target + * @param {Date} source + * @returns {Date} the target after modifications + */ + function mirrorDateProperties(target, source) { + let prop; + for (prop in source) { + if (source.hasOwnProperty(prop)) { + target[prop] = source[prop]; + } + } + + // set special now implementation + if (source.now) { + target.now = function now() { + return target.clock.now; + }; + } else { + delete target.now; + } + + // set special toSource implementation + if (source.toSource) { + target.toSource = function toSource() { + return source.toSource(); + }; + } else { + delete target.toSource; + } + + // set special toString implementation + target.toString = function toString() { + return source.toString(); + }; + + target.prototype = source.prototype; + target.parse = source.parse; + target.UTC = source.UTC; + target.prototype.toUTCString = source.prototype.toUTCString; + target.isFake = true; + + return target; + } + + //eslint-disable-next-line jsdoc/require-jsdoc + function createDate() { + /** + * @param {number} year + * @param {number} month + * @param {number} date + * @param {number} hour + * @param {number} minute + * @param {number} second + * @param {number} ms + * @returns {Date} + */ + function ClockDate(year, month, date, hour, minute, second, ms) { + // the Date constructor called as a function, ref Ecma-262 Edition 5.1, section 15.9.2. + // This remains so in the 10th edition of 2019 as well. + if (!(this instanceof ClockDate)) { + return new NativeDate(ClockDate.clock.now).toString(); + } + + // if Date is called as a constructor with 'new' keyword + // Defensive and verbose to avoid potential harm in passing + // explicit undefined when user does not pass argument + switch (arguments.length) { + case 0: + return new NativeDate(ClockDate.clock.now); + case 1: + return new NativeDate(year); + case 2: + return new NativeDate(year, month); + case 3: + return new NativeDate(year, month, date); + case 4: + return new NativeDate(year, month, date, hour); + case 5: + return new NativeDate(year, month, date, hour, minute); + case 6: + return new NativeDate( + year, + month, + date, + hour, + minute, + second + ); + default: + return new NativeDate( + year, + month, + date, + hour, + minute, + second, + ms + ); + } + } + + return mirrorDateProperties(ClockDate, NativeDate); + } + + //eslint-disable-next-line jsdoc/require-jsdoc + function enqueueJob(clock, job) { + // enqueues a microtick-deferred task - ecma262/#sec-enqueuejob + if (!clock.jobs) { + clock.jobs = []; + } + clock.jobs.push(job); + } + + //eslint-disable-next-line jsdoc/require-jsdoc + function runJobs(clock) { + // runs all microtick-deferred tasks - ecma262/#sec-runjobs + if (!clock.jobs) { + return; + } + for (let i = 0; i < clock.jobs.length; i++) { + const job = clock.jobs[i]; + job.func.apply(null, job.args); + + checkIsNearInfiniteLimit(clock, i); + if (clock.loopLimit && i > clock.loopLimit) { + throw getInfiniteLoopError(clock, job); + } + } + resetIsNearInfiniteLimit(); + clock.jobs = []; + } + + /** + * @param {Clock} clock + * @param {Timer} timer + * @returns {number} id of the created timer + */ + function addTimer(clock, timer) { + if (timer.func === undefined) { + throw new Error("Callback must be provided to timer calls"); + } + + if (addTimerReturnsObject) { + // Node.js environment + if (typeof timer.func !== "function") { + throw new TypeError( + `[ERR_INVALID_CALLBACK]: Callback must be a function. Received ${ + timer.func + } of type ${typeof timer.func}` + ); + } + } + + if (isNearInfiniteLimit) { + timer.error = new Error(); + } + + timer.type = timer.immediate ? "Immediate" : "Timeout"; + + if (timer.hasOwnProperty("delay")) { + if (typeof timer.delay !== "number") { + timer.delay = parseInt(timer.delay, 10); + } + + if (!isNumberFinite(timer.delay)) { + timer.delay = 0; + } + timer.delay = timer.delay > maxTimeout ? 1 : timer.delay; + timer.delay = Math.max(0, timer.delay); + } + + if (timer.hasOwnProperty("interval")) { + timer.type = "Interval"; + timer.interval = timer.interval > maxTimeout ? 1 : timer.interval; + } + + if (timer.hasOwnProperty("animation")) { + timer.type = "AnimationFrame"; + timer.animation = true; + } + + if (timer.hasOwnProperty("idleCallback")) { + timer.type = "IdleCallback"; + timer.idleCallback = true; + } + + if (!clock.timers) { + clock.timers = {}; + } + + timer.id = uniqueTimerId++; + timer.createdAt = clock.now; + timer.callAt = + clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0)); + + clock.timers[timer.id] = timer; + + if (addTimerReturnsObject) { + const res = { + refed: true, + ref: function () { + this.refed = true; + return res; + }, + unref: function () { + this.refed = false; + return res; + }, + hasRef: function () { + return this.refed; + }, + refresh: function () { + timer.callAt = + clock.now + + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0)); + + // it _might_ have been removed, but if not the assignment is perfectly fine + clock.timers[timer.id] = timer; + + return res; + }, + [Symbol.toPrimitive]: function () { + return timer.id; + }, + }; + return res; + } + + return timer.id; + } + + /* eslint consistent-return: "off" */ + /** + * Timer comparitor + * + * @param {Timer} a + * @param {Timer} b + * @returns {number} + */ + function compareTimers(a, b) { + // Sort first by absolute timing + if (a.callAt < b.callAt) { + return -1; + } + if (a.callAt > b.callAt) { + return 1; + } + + // Sort next by immediate, immediate timers take precedence + if (a.immediate && !b.immediate) { + return -1; + } + if (!a.immediate && b.immediate) { + return 1; + } + + // Sort next by creation time, earlier-created timers take precedence + if (a.createdAt < b.createdAt) { + return -1; + } + if (a.createdAt > b.createdAt) { + return 1; + } + + // Sort next by id, lower-id timers take precedence + if (a.id < b.id) { + return -1; + } + if (a.id > b.id) { + return 1; + } + + // As timer ids are unique, no fallback `0` is necessary + } + + /** + * @param {Clock} clock + * @param {number} from + * @param {number} to + * @returns {Timer} + */ + function firstTimerInRange(clock, from, to) { + const timers = clock.timers; + let timer = null; + let id, isInRange; + + for (id in timers) { + if (timers.hasOwnProperty(id)) { + isInRange = inRange(from, to, timers[id]); + + if ( + isInRange && + (!timer || compareTimers(timer, timers[id]) === 1) + ) { + timer = timers[id]; + } + } + } + + return timer; + } + + /** + * @param {Clock} clock + * @returns {Timer} + */ + function firstTimer(clock) { + const timers = clock.timers; + let timer = null; + let id; + + for (id in timers) { + if (timers.hasOwnProperty(id)) { + if (!timer || compareTimers(timer, timers[id]) === 1) { + timer = timers[id]; + } + } + } + + return timer; + } + + /** + * @param {Clock} clock + * @returns {Timer} + */ + function lastTimer(clock) { + const timers = clock.timers; + let timer = null; + let id; + + for (id in timers) { + if (timers.hasOwnProperty(id)) { + if (!timer || compareTimers(timer, timers[id]) === -1) { + timer = timers[id]; + } + } + } + + return timer; + } + + /** + * @param {Clock} clock + * @param {Timer} timer + */ + function callTimer(clock, timer) { + if (typeof timer.interval === "number") { + clock.timers[timer.id].callAt += timer.interval; + } else { + delete clock.timers[timer.id]; + } + + if (typeof timer.func === "function") { + timer.func.apply(null, timer.args); + } else { + /* eslint no-eval: "off" */ + const eval2 = eval; + (function () { + eval2(timer.func); + })(); + } + } + + /** + * Gets clear handler name for a given timer type + * + * @param {string} ttype + */ + function getClearHandler(ttype) { + if (ttype === "IdleCallback" || ttype === "AnimationFrame") { + return `cancel${ttype}`; + } + return `clear${ttype}`; + } + + /** + * Gets schedule handler name for a given timer type + * + * @param {string} ttype + */ + function getScheduleHandler(ttype) { + if (ttype === "IdleCallback" || ttype === "AnimationFrame") { + return `request${ttype}`; + } + return `set${ttype}`; + } + + /** + * Creates an anonymous function to warn only once + */ + function createWarnOnce() { + let calls = 0; + return function (msg) { + // eslint-disable-next-line + !calls++ && console.warn(msg); + }; + } + const warnOnce = createWarnOnce(); + + /** + * @param {Clock} clock + * @param {number} timerId + * @param {string} ttype + */ + function clearTimer(clock, timerId, ttype) { + if (!timerId) { + // null appears to be allowed in most browsers, and appears to be + // relied upon by some libraries, like Bootstrap carousel + return; + } + + if (!clock.timers) { + clock.timers = {}; + } + + // in Node, the ID is stored as the primitive value for `Timeout` objects + // for `Immediate` objects, no ID exists, so it gets coerced to NaN + const id = Number(timerId); + + if (Number.isNaN(id) || id < idCounterStart) { + const handlerName = getClearHandler(ttype); + + if (clock.shouldClearNativeTimers === true) { + const nativeHandler = clock[`_${handlerName}`]; + return typeof nativeHandler === "function" + ? nativeHandler(timerId) + : undefined; + } + warnOnce( + `FakeTimers: ${handlerName} was invoked to clear a native timer instead of one created by this library.` + + "\nTo automatically clean-up native timers, use `shouldClearNativeTimers`." + ); + } + + if (clock.timers.hasOwnProperty(id)) { + // check that the ID matches a timer of the correct type + const timer = clock.timers[id]; + if ( + timer.type === ttype || + (timer.type === "Timeout" && ttype === "Interval") || + (timer.type === "Interval" && ttype === "Timeout") + ) { + delete clock.timers[id]; + } else { + const clear = getClearHandler(ttype); + const schedule = getScheduleHandler(timer.type); + throw new Error( + `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()` + ); + } + } + } + + /** + * @param {Clock} clock + * @param {Config} config + * @returns {Timer[]} + */ + function uninstall(clock, config) { + let method, i, l; + const installedHrTime = "_hrtime"; + const installedNextTick = "_nextTick"; + + for (i = 0, l = clock.methods.length; i < l; i++) { + method = clock.methods[i]; + if (method === "hrtime" && _global.process) { + _global.process.hrtime = clock[installedHrTime]; + } else if (method === "nextTick" && _global.process) { + _global.process.nextTick = clock[installedNextTick]; + } else if (method === "performance") { + const originalPerfDescriptor = Object.getOwnPropertyDescriptor( + clock, + `_${method}` + ); + if ( + originalPerfDescriptor && + originalPerfDescriptor.get && + !originalPerfDescriptor.set + ) { + Object.defineProperty( + _global, + method, + originalPerfDescriptor + ); + } else if (originalPerfDescriptor.configurable) { + _global[method] = clock[`_${method}`]; + } + } else { + if (_global[method] && _global[method].hadOwnProperty) { + _global[method] = clock[`_${method}`]; + } else { + try { + delete _global[method]; + } catch (ignore) { + /* eslint no-empty: "off" */ + } + } + } + } + + if (config.shouldAdvanceTime === true) { + _global.clearInterval(clock.attachedInterval); + } + + // Prevent multiple executions which will completely remove these props + clock.methods = []; + + // return pending timers, to enable checking what timers remained on uninstall + if (!clock.timers) { + return []; + } + return Object.keys(clock.timers).map(function mapper(key) { + return clock.timers[key]; + }); + } + + /** + * @param {object} target the target containing the method to replace + * @param {string} method the keyname of the method on the target + * @param {Clock} clock + */ + function hijackMethod(target, method, clock) { + clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call( + target, + method + ); + clock[`_${method}`] = target[method]; + + if (method === "Date") { + const date = mirrorDateProperties(clock[method], target[method]); + target[method] = date; + } else if (method === "performance") { + const originalPerfDescriptor = Object.getOwnPropertyDescriptor( + target, + method + ); + // JSDOM has a read only performance field so we have to save/copy it differently + if ( + originalPerfDescriptor && + originalPerfDescriptor.get && + !originalPerfDescriptor.set + ) { + Object.defineProperty( + clock, + `_${method}`, + originalPerfDescriptor + ); + + const perfDescriptor = Object.getOwnPropertyDescriptor( + clock, + method + ); + Object.defineProperty(target, method, perfDescriptor); + } else { + target[method] = clock[method]; + } + } else { + target[method] = function () { + return clock[method].apply(clock, arguments); + }; + + Object.defineProperties( + target[method], + Object.getOwnPropertyDescriptors(clock[method]) + ); + } + + target[method].clock = clock; + } + + /** + * @param {Clock} clock + * @param {number} advanceTimeDelta + */ + function doIntervalTick(clock, advanceTimeDelta) { + clock.tick(advanceTimeDelta); + } + + /** + * @typedef {object} Timers + * @property {setTimeout} setTimeout + * @property {clearTimeout} clearTimeout + * @property {setInterval} setInterval + * @property {clearInterval} clearInterval + * @property {Date} Date + * @property {SetImmediate=} setImmediate + * @property {function(NodeImmediate): void=} clearImmediate + * @property {function(number[]):number[]=} hrtime + * @property {NextTick=} nextTick + * @property {Performance=} performance + * @property {RequestAnimationFrame=} requestAnimationFrame + * @property {boolean=} queueMicrotask + * @property {function(number): void=} cancelAnimationFrame + * @property {RequestIdleCallback=} requestIdleCallback + * @property {function(number): void=} cancelIdleCallback + */ + + /** @type {Timers} */ + const timers = { + setTimeout: _global.setTimeout, + clearTimeout: _global.clearTimeout, + setInterval: _global.setInterval, + clearInterval: _global.clearInterval, + Date: _global.Date, + }; + + if (setImmediatePresent) { + timers.setImmediate = _global.setImmediate; + timers.clearImmediate = _global.clearImmediate; + } + + if (hrtimePresent) { + timers.hrtime = _global.process.hrtime; + } + + if (nextTickPresent) { + timers.nextTick = _global.process.nextTick; + } + + if (performancePresent) { + timers.performance = _global.performance; + } + + if (requestAnimationFramePresent) { + timers.requestAnimationFrame = _global.requestAnimationFrame; + } + + if (queueMicrotaskPresent) { + timers.queueMicrotask = true; + } + + if (cancelAnimationFramePresent) { + timers.cancelAnimationFrame = _global.cancelAnimationFrame; + } + + if (requestIdleCallbackPresent) { + timers.requestIdleCallback = _global.requestIdleCallback; + } + + if (cancelIdleCallbackPresent) { + timers.cancelIdleCallback = _global.cancelIdleCallback; + } + + const originalSetTimeout = _global.setImmediate || _global.setTimeout; + + /** + * @param {Date|number} [start] the system time - non-integer values are floored + * @param {number} [loopLimit] maximum number of timers that will be run when calling runAll() + * @returns {Clock} + */ + function createClock(start, loopLimit) { + // eslint-disable-next-line no-param-reassign + start = Math.floor(getEpoch(start)); + // eslint-disable-next-line no-param-reassign + loopLimit = loopLimit || 1000; + let nanos = 0; + const adjustedSystemTime = [0, 0]; // [millis, nanoremainder] + + if (NativeDate === undefined) { + throw new Error( + "The global scope doesn't have a `Date` object" + + " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)" + ); + } + + const clock = { + now: start, + Date: createDate(), + loopLimit: loopLimit, + }; + + clock.Date.clock = clock; + + //eslint-disable-next-line jsdoc/require-jsdoc + function getTimeToNextFrame() { + return 16 - ((clock.now - start) % 16); + } + + //eslint-disable-next-line jsdoc/require-jsdoc + function hrtime(prev) { + const millisSinceStart = clock.now - adjustedSystemTime[0] - start; + const secsSinceStart = Math.floor(millisSinceStart / 1000); + const remainderInNanos = + (millisSinceStart - secsSinceStart * 1e3) * 1e6 + + nanos - + adjustedSystemTime[1]; + + if (Array.isArray(prev)) { + if (prev[1] > 1e9) { + throw new TypeError( + "Number of nanoseconds can't exceed a billion" + ); + } + + const oldSecs = prev[0]; + let nanoDiff = remainderInNanos - prev[1]; + let secDiff = secsSinceStart - oldSecs; + + if (nanoDiff < 0) { + nanoDiff += 1e9; + secDiff -= 1; + } + + return [secDiff, nanoDiff]; + } + return [secsSinceStart, remainderInNanos]; + } + + function fakePerformanceNow() { + const hrt = hrtime(); + const millis = hrt[0] * 1000 + hrt[1] / 1e6; + return millis; + } + + if (hrtimeBigintPresent) { + hrtime.bigint = function () { + const parts = hrtime(); + return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]); // eslint-disable-line + }; + } + + clock.requestIdleCallback = function requestIdleCallback( + func, + timeout + ) { + let timeToNextIdlePeriod = 0; + + if (clock.countTimers() > 0) { + timeToNextIdlePeriod = 50; // const for now + } + + const result = addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 2), + delay: + typeof timeout === "undefined" + ? timeToNextIdlePeriod + : Math.min(timeout, timeToNextIdlePeriod), + idleCallback: true, + }); + + return Number(result); + }; + + clock.cancelIdleCallback = function cancelIdleCallback(timerId) { + return clearTimer(clock, timerId, "IdleCallback"); + }; + + clock.setTimeout = function setTimeout(func, timeout) { + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 2), + delay: timeout, + }); + }; + if (typeof _global.Promise !== "undefined" && utilPromisify) { + clock.setTimeout[utilPromisify.custom] = + function promisifiedSetTimeout(timeout, arg) { + return new _global.Promise(function setTimeoutExecutor( + resolve + ) { + addTimer(clock, { + func: resolve, + args: [arg], + delay: timeout, + }); + }); + }; + } + + clock.clearTimeout = function clearTimeout(timerId) { + return clearTimer(clock, timerId, "Timeout"); + }; + + clock.nextTick = function nextTick(func) { + return enqueueJob(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 1), + error: isNearInfiniteLimit ? new Error() : null, + }); + }; + + clock.queueMicrotask = function queueMicrotask(func) { + return clock.nextTick(func); // explicitly drop additional arguments + }; + + clock.setInterval = function setInterval(func, timeout) { + // eslint-disable-next-line no-param-reassign + timeout = parseInt(timeout, 10); + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 2), + delay: timeout, + interval: timeout, + }); + }; + + clock.clearInterval = function clearInterval(timerId) { + return clearTimer(clock, timerId, "Interval"); + }; + + if (setImmediatePresent) { + clock.setImmediate = function setImmediate(func) { + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 1), + immediate: true, + }); + }; + + if (typeof _global.Promise !== "undefined" && utilPromisify) { + clock.setImmediate[utilPromisify.custom] = + function promisifiedSetImmediate(arg) { + return new _global.Promise( + function setImmediateExecutor(resolve) { + addTimer(clock, { + func: resolve, + args: [arg], + immediate: true, + }); + } + ); + }; + } + + clock.clearImmediate = function clearImmediate(timerId) { + return clearTimer(clock, timerId, "Immediate"); + }; + } + + clock.countTimers = function countTimers() { + return ( + Object.keys(clock.timers || {}).length + + (clock.jobs || []).length + ); + }; + + clock.requestAnimationFrame = function requestAnimationFrame(func) { + const result = addTimer(clock, { + func: func, + delay: getTimeToNextFrame(), + get args() { + return [fakePerformanceNow()]; + }, + animation: true, + }); + + return Number(result); + }; + + clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) { + return clearTimer(clock, timerId, "AnimationFrame"); + }; + + clock.runMicrotasks = function runMicrotasks() { + runJobs(clock); + }; + + /** + * @param {number|string} tickValue milliseconds or a string parseable by parseTime + * @param {boolean} isAsync + * @param {Function} resolve + * @param {Function} reject + * @returns {number|undefined} will return the new `now` value or nothing for async + */ + function doTick(tickValue, isAsync, resolve, reject) { + const msFloat = + typeof tickValue === "number" + ? tickValue + : parseTime(tickValue); + const ms = Math.floor(msFloat); + const remainder = nanoRemainder(msFloat); + let nanosTotal = nanos + remainder; + let tickTo = clock.now + ms; + + if (msFloat < 0) { + throw new TypeError("Negative ticks are not supported"); + } + + // adjust for positive overflow + if (nanosTotal >= 1e6) { + tickTo += 1; + nanosTotal -= 1e6; + } + + nanos = nanosTotal; + let tickFrom = clock.now; + let previous = clock.now; + // ESLint fails to detect this correctly + /* eslint-disable prefer-const */ + let timer, + firstException, + oldNow, + nextPromiseTick, + compensationCheck, + postTimerCall; + /* eslint-enable prefer-const */ + + clock.duringTick = true; + + // perform microtasks + oldNow = clock.now; + runJobs(clock); + if (oldNow !== clock.now) { + // compensate for any setSystemTime() call during microtask callback + tickFrom += clock.now - oldNow; + tickTo += clock.now - oldNow; + } + + //eslint-disable-next-line jsdoc/require-jsdoc + function doTickInner() { + // perform each timer in the requested range + timer = firstTimerInRange(clock, tickFrom, tickTo); + // eslint-disable-next-line no-unmodified-loop-condition + while (timer && tickFrom <= tickTo) { + if (clock.timers[timer.id]) { + tickFrom = timer.callAt; + clock.now = timer.callAt; + oldNow = clock.now; + try { + runJobs(clock); + callTimer(clock, timer); + } catch (e) { + firstException = firstException || e; + } + + if (isAsync) { + // finish up after native setImmediate callback to allow + // all native es6 promises to process their callbacks after + // each timer fires. + originalSetTimeout(nextPromiseTick); + return; + } + + compensationCheck(); + } + + postTimerCall(); + } + + // perform process.nextTick()s again + oldNow = clock.now; + runJobs(clock); + if (oldNow !== clock.now) { + // compensate for any setSystemTime() call during process.nextTick() callback + tickFrom += clock.now - oldNow; + tickTo += clock.now - oldNow; + } + clock.duringTick = false; + + // corner case: during runJobs new timers were scheduled which could be in the range [clock.now, tickTo] + timer = firstTimerInRange(clock, tickFrom, tickTo); + if (timer) { + try { + clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range + } catch (e) { + firstException = firstException || e; + } + } else { + // no timers remaining in the requested range: move the clock all the way to the end + clock.now = tickTo; + + // update nanos + nanos = nanosTotal; + } + if (firstException) { + throw firstException; + } + + if (isAsync) { + resolve(clock.now); + } else { + return clock.now; + } + } + + nextPromiseTick = + isAsync && + function () { + try { + compensationCheck(); + postTimerCall(); + doTickInner(); + } catch (e) { + reject(e); + } + }; + + compensationCheck = function () { + // compensate for any setSystemTime() call during timer callback + if (oldNow !== clock.now) { + tickFrom += clock.now - oldNow; + tickTo += clock.now - oldNow; + previous += clock.now - oldNow; + } + }; + + postTimerCall = function () { + timer = firstTimerInRange(clock, previous, tickTo); + previous = tickFrom; + }; + + return doTickInner(); + } + + /** + * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15" + * @returns {number} will return the new `now` value + */ + clock.tick = function tick(tickValue) { + return doTick(tickValue, false); + }; + + if (typeof _global.Promise !== "undefined") { + /** + * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15" + * @returns {Promise} + */ + clock.tickAsync = function tickAsync(tickValue) { + return new _global.Promise(function (resolve, reject) { + originalSetTimeout(function () { + try { + doTick(tickValue, true, resolve, reject); + } catch (e) { + reject(e); + } + }); + }); + }; + } + + clock.next = function next() { + runJobs(clock); + const timer = firstTimer(clock); + if (!timer) { + return clock.now; + } + + clock.duringTick = true; + try { + clock.now = timer.callAt; + callTimer(clock, timer); + runJobs(clock); + return clock.now; + } finally { + clock.duringTick = false; + } + }; + + if (typeof _global.Promise !== "undefined") { + clock.nextAsync = function nextAsync() { + return new _global.Promise(function (resolve, reject) { + originalSetTimeout(function () { + try { + const timer = firstTimer(clock); + if (!timer) { + resolve(clock.now); + return; + } + + let err; + clock.duringTick = true; + clock.now = timer.callAt; + try { + callTimer(clock, timer); + } catch (e) { + err = e; + } + clock.duringTick = false; + + originalSetTimeout(function () { + if (err) { + reject(err); + } else { + resolve(clock.now); + } + }); + } catch (e) { + reject(e); + } + }); + }); + }; + } + + clock.runAll = function runAll() { + let numTimers, i; + runJobs(clock); + for (i = 0; i < clock.loopLimit; i++) { + if (!clock.timers) { + resetIsNearInfiniteLimit(); + return clock.now; + } + + numTimers = Object.keys(clock.timers).length; + if (numTimers === 0) { + resetIsNearInfiniteLimit(); + return clock.now; + } + + clock.next(); + checkIsNearInfiniteLimit(clock, i); + } + + const excessJob = firstTimer(clock); + throw getInfiniteLoopError(clock, excessJob); + }; + + clock.runToFrame = function runToFrame() { + return clock.tick(getTimeToNextFrame()); + }; + + if (typeof _global.Promise !== "undefined") { + clock.runAllAsync = function runAllAsync() { + return new _global.Promise(function (resolve, reject) { + let i = 0; + /** + * + */ + function doRun() { + originalSetTimeout(function () { + try { + let numTimers; + if (i < clock.loopLimit) { + if (!clock.timers) { + resetIsNearInfiniteLimit(); + resolve(clock.now); + return; + } + + numTimers = Object.keys( + clock.timers + ).length; + if (numTimers === 0) { + resetIsNearInfiniteLimit(); + resolve(clock.now); + return; + } + + clock.next(); + + i++; + + doRun(); + checkIsNearInfiniteLimit(clock, i); + return; + } + + const excessJob = firstTimer(clock); + reject(getInfiniteLoopError(clock, excessJob)); + } catch (e) { + reject(e); + } + }); + } + doRun(); + }); + }; + } + + clock.runToLast = function runToLast() { + const timer = lastTimer(clock); + if (!timer) { + runJobs(clock); + return clock.now; + } + + return clock.tick(timer.callAt - clock.now); + }; + + if (typeof _global.Promise !== "undefined") { + clock.runToLastAsync = function runToLastAsync() { + return new _global.Promise(function (resolve, reject) { + originalSetTimeout(function () { + try { + const timer = lastTimer(clock); + if (!timer) { + resolve(clock.now); + } + + resolve(clock.tickAsync(timer.callAt - clock.now)); + } catch (e) { + reject(e); + } + }); + }); + }; + } + + clock.reset = function reset() { + nanos = 0; + clock.timers = {}; + clock.jobs = []; + clock.now = start; + }; + + clock.setSystemTime = function setSystemTime(systemTime) { + // determine time difference + const newNow = getEpoch(systemTime); + const difference = newNow - clock.now; + let id, timer; + + adjustedSystemTime[0] = adjustedSystemTime[0] + difference; + adjustedSystemTime[1] = adjustedSystemTime[1] + nanos; + // update 'system clock' + clock.now = newNow; + nanos = 0; + + // update timers and intervals to keep them stable + for (id in clock.timers) { + if (clock.timers.hasOwnProperty(id)) { + timer = clock.timers[id]; + timer.createdAt += difference; + timer.callAt += difference; + } + } + }; + + if (performancePresent) { + clock.performance = Object.create(null); + clock.performance.now = fakePerformanceNow; + } + + if (hrtimePresent) { + clock.hrtime = hrtime; + } + + return clock; + } + + /* eslint-disable complexity */ + + /** + * @param {Config=} [config] Optional config + * @returns {Clock} + */ + function install(config) { + if ( + arguments.length > 1 || + config instanceof Date || + Array.isArray(config) || + typeof config === "number" + ) { + throw new TypeError( + `FakeTimers.install called with ${String( + config + )} install requires an object parameter` + ); + } + + if (_global.Date.isFake === true) { + // Timers are already faked; this is a problem. + // Make the user reset timers before continuing. + throw new TypeError( + "Can't install fake timers twice on the same global object." + ); + } + + // eslint-disable-next-line no-param-reassign + config = typeof config !== "undefined" ? config : {}; + config.shouldAdvanceTime = config.shouldAdvanceTime || false; + config.advanceTimeDelta = config.advanceTimeDelta || 20; + config.shouldClearNativeTimers = + config.shouldClearNativeTimers || false; + + if (config.target) { + throw new TypeError( + "config.target is no longer supported. Use `withGlobal(target)` instead." + ); + } + + let i, l; + const clock = createClock(config.now, config.loopLimit); + clock.shouldClearNativeTimers = config.shouldClearNativeTimers; + + clock.uninstall = function () { + return uninstall(clock, config); + }; + + clock.methods = config.toFake || []; + + if (clock.methods.length === 0) { + // do not fake nextTick by default - GitHub#126 + clock.methods = Object.keys(timers).filter(function (key) { + return key !== "nextTick" && key !== "queueMicrotask"; + }); + } + + if (config.shouldAdvanceTime === true) { + const intervalTick = doIntervalTick.bind( + null, + clock, + config.advanceTimeDelta + ); + const intervalId = _global.setInterval( + intervalTick, + config.advanceTimeDelta + ); + clock.attachedInterval = intervalId; + } + + if (clock.methods.includes("performance")) { + const proto = (() => { + if (hasPerformancePrototype) { + return _global.Performance.prototype; + } + if (hasPerformanceConstructorPrototype) { + return _global.performance.constructor.prototype; + } + })(); + if (proto) { + Object.getOwnPropertyNames(proto).forEach(function (name) { + if (name !== "now") { + clock.performance[name] = + name.indexOf("getEntries") === 0 + ? NOOP_ARRAY + : NOOP; + } + }); + } else if ((config.toFake || []).includes("performance")) { + // user explicitly tried to fake performance when not present + throw new ReferenceError( + "non-existent performance object cannot be faked" + ); + } + } + + for (i = 0, l = clock.methods.length; i < l; i++) { + const nameOfMethodToReplace = clock.methods[i]; + if (nameOfMethodToReplace === "hrtime") { + if ( + _global.process && + typeof _global.process.hrtime === "function" + ) { + hijackMethod(_global.process, nameOfMethodToReplace, clock); + } + } else if (nameOfMethodToReplace === "nextTick") { + if ( + _global.process && + typeof _global.process.nextTick === "function" + ) { + hijackMethod(_global.process, nameOfMethodToReplace, clock); + } + } else { + hijackMethod(_global, nameOfMethodToReplace, clock); + } + } + + return clock; + } + + /* eslint-enable complexity */ + + return { + timers: timers, + createClock: createClock, + install: install, + withGlobal: withGlobal, + }; +} + +/** + * @typedef {object} FakeTimers + * @property {Timers} timers + * @property {createClock} createClock + * @property {Function} install + * @property {withGlobal} withGlobal + */ + +/* eslint-enable complexity */ + +/** @type {FakeTimers} */ +const defaultImplementation = withGlobal(globalObject); + +defaultImplementation.timers; +defaultImplementation.createClock; +defaultImplementation.install; +var withGlobal_1 = withGlobal; + +class FakeTimers { + constructor({ + global, + config + }) { + this._now = RealDate.now; + this._userConfig = config; + this._fakingDate = false; + this._fakingTime = false; + this._fakeTimers = withGlobal_1(global); + } + clearAllTimers() { + if (this._fakingTime) + this._clock.reset(); + } + dispose() { + this.useRealTimers(); + } + runAllTimers() { + if (this._checkFakeTimers()) + this._clock.runAll(); + } + runOnlyPendingTimers() { + if (this._checkFakeTimers()) + this._clock.runToLast(); + } + advanceTimersToNextTimer(steps = 1) { + if (this._checkFakeTimers()) { + for (let i = steps; i > 0; i--) { + this._clock.next(); + this._clock.tick(0); + if (this._clock.countTimers() === 0) + break; + } + } + } + advanceTimersByTime(msToRun) { + if (this._checkFakeTimers()) + this._clock.tick(msToRun); + } + runAllTicks() { + if (this._checkFakeTimers()) { + this._clock.runMicrotasks(); + } + } + useRealTimers() { + if (this._fakingDate) { + resetDate(); + this._fakingDate = false; + } + if (this._fakingTime) { + this._clock.uninstall(); + this._fakingTime = false; + } + } + useFakeTimers() { + if (this._fakingDate) { + throw new Error( + '"setSystemTime" was called already and date was mocked. Reset timers using `vi.useRealTimers()` if you want to use fake timers again.' + ); + } + if (!this._fakingTime) { + const toFake = Object.keys(this._fakeTimers.timers); + this._clock = this._fakeTimers.install({ + now: Date.now(), + toFake, + ...this._userConfig + }); + this._fakingTime = true; + } + } + reset() { + if (this._checkFakeTimers()) { + const { now } = this._clock; + this._clock.reset(); + this._clock.setSystemTime(now); + } + } + setSystemTime(now) { + if (this._fakingTime) { + this._clock.setSystemTime(now); + } else { + mockDate(now ?? this.getRealSystemTime()); + this._fakingDate = true; + } + } + getRealSystemTime() { + return this._now(); + } + getTimerCount() { + if (this._checkFakeTimers()) + return this._clock.countTimers(); + return 0; + } + configure(config) { + this._userConfig = config; + } + _checkFakeTimers() { + if (!this._fakingTime) { + throw new Error( + 'Timers are not mocked. Try calling "vi.useFakeTimers()" first.' + ); + } + return this._fakingTime; + } +} + +class VitestUtils { + constructor() { + this.spyOn = spyOn; + this.fn = fn; + this._stubsGlobal = /* @__PURE__ */ new Map(); + this._stubsEnv = /* @__PURE__ */ new Map(); + this._config = null; + this._mocker = typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : null; + this._mockedDate = null; + if (!this._mocker) { + const errorMsg = 'Vitest was initialized with native Node instead of Vite Node.\n\nOne of the following is possible:\n- "vitest" is imported outside of your tests (in that case, use "vitest/node" or import.meta.vitest)\n- "vitest" is imported inside "globalSetup" (use "setupFiles", because "globalSetup" runs in a different context)\n- Your dependency inside "node_modules" imports "vitest" directly (in that case, inline that dependency, using "deps.inline" config)\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n'; + throw new Error(errorMsg); + } + const workerState = getWorkerState(); + this._timers = new FakeTimers({ + global: globalThis, + config: workerState.config.fakeTimers + }); + } + useFakeTimers(config) { + if (config) { + this._timers.configure(config); + } else { + const workerState = getWorkerState(); + this._timers.configure(workerState.config.fakeTimers); + } + this._timers.useFakeTimers(); + return this; + } + useRealTimers() { + this._timers.useRealTimers(); + this._mockedDate = null; + return this; + } + runOnlyPendingTimers() { + this._timers.runOnlyPendingTimers(); + return this; + } + runAllTimers() { + this._timers.runAllTimers(); + return this; + } + runAllTicks() { + this._timers.runAllTicks(); + return this; + } + advanceTimersByTime(ms) { + this._timers.advanceTimersByTime(ms); + return this; + } + advanceTimersToNextTimer() { + this._timers.advanceTimersToNextTimer(); + return this; + } + getTimerCount() { + return this._timers.getTimerCount(); + } + setSystemTime(time) { + const date = time instanceof Date ? time : new Date(time); + this._mockedDate = date; + this._timers.setSystemTime(date); + return this; + } + getMockedSystemTime() { + return this._mockedDate; + } + getRealSystemTime() { + return this._timers.getRealSystemTime(); + } + clearAllTimers() { + this._timers.clearAllTimers(); + return this; + } + getImporter() { + const stackTrace = createSimpleStackTrace({ stackTraceLimit: 4 }); + const importerStack = stackTrace.split("\n")[4]; + const stack = parseSingleStack(importerStack); + return (stack == null ? void 0 : stack.file) || ""; + } + mock(path, factory) { + const importer = this.getImporter(); + this._mocker.queueMock( + path, + importer, + factory ? () => factory(() => this._mocker.importActual(path, importer)) : void 0 + ); + } + unmock(path) { + this._mocker.queueUnmock(path, this.getImporter()); + } + doMock(path, factory) { + this._mocker.queueMock(path, this.getImporter(), factory); + } + doUnmock(path) { + this._mocker.queueUnmock(path, this.getImporter()); + } + async importActual(path) { + return this._mocker.importActual(path, this.getImporter()); + } + async importMock(path) { + return this._mocker.importMock(path, this.getImporter()); + } + mocked(item, _options = {}) { + return item; + } + isMockFunction(fn2) { + return isMockFunction(fn2); + } + clearAllMocks() { + spies.forEach((spy) => spy.mockClear()); + return this; + } + resetAllMocks() { + spies.forEach((spy) => spy.mockReset()); + return this; + } + restoreAllMocks() { + spies.forEach((spy) => spy.mockRestore()); + return this; + } + stubGlobal(name, value) { + if (!this._stubsGlobal.has(name)) + this._stubsGlobal.set(name, Object.getOwnPropertyDescriptor(globalThis, name)); + globalThis[name] = value; + return this; + } + stubEnv(name, value) { + if (!this._stubsEnv.has(name)) + this._stubsEnv.set(name, process.env[name]); + process.env[name] = value; + return this; + } + unstubAllGlobals() { + this._stubsGlobal.forEach((original, name) => { + if (!original) + Reflect.deleteProperty(globalThis, name); + else + Object.defineProperty(globalThis, name, original); + }); + this._stubsGlobal.clear(); + return this; + } + unstubAllEnvs() { + this._stubsEnv.forEach((original, name) => { + if (original === void 0) + delete process.env[name]; + else + process.env[name] = original; + }); + this._stubsEnv.clear(); + return this; + } + resetModules() { + const state = getWorkerState(); + resetModules(state.moduleCache); + return this; + } + async dynamicImportSettled() { + return waitForImportsToResolve(); + } + setConfig(config) { + const state = getWorkerState(); + if (!this._config) + this._config = { ...state.config }; + Object.assign(state.config, config); + } + resetConfig() { + if (this._config) { + const state = getWorkerState(); + state.config = { ...this._config }; + } + } +} +const vitest = new VitestUtils(); +const vi = vitest; + +function getRunningMode() { + return process.env.VITEST_MODE === "WATCH" ? "watch" : "run"; +} +function isWatchMode() { + return getRunningMode() === "watch"; +} + +var dist = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.expectTypeOf = void 0; + const fn = () => true; + /** + * Similar to Jest's `expect`, but with type-awareness. + * Gives you access to a number of type-matchers that let you make assertions about the + * form of a reference or generic type parameter. + * + * @example + * import {foo, bar} from '../foo' + * import {expectTypeOf} from 'expect-type' + * + * test('foo types', () => { + * // make sure `foo` has type {a: number} + * expectTypeOf(foo).toMatchTypeOf({a: 1}) + * expectTypeOf(foo).toHaveProperty('a').toBeNumber() + * + * // make sure `bar` is a function taking a string: + * expectTypeOf(bar).parameter(0).toBeString() + * expectTypeOf(bar).returns.not.toBeAny() + * }) + * + * @description + * See the [full docs](https://npmjs.com/package/expect-type#documentation) for lots more examples. + */ + const expectTypeOf = (_actual) => { + const nonFunctionProperties = [ + 'parameters', + 'returns', + 'resolves', + 'not', + 'items', + 'constructorParameters', + 'instance', + 'guards', + 'asserts', + ]; + const obj = { + /* eslint-disable mmkal/@typescript-eslint/no-unsafe-assignment */ + toBeAny: fn, + toBeUnknown: fn, + toBeNever: fn, + toBeFunction: fn, + toBeObject: fn, + toBeArray: fn, + toBeString: fn, + toBeNumber: fn, + toBeBoolean: fn, + toBeVoid: fn, + toBeSymbol: fn, + toBeNull: fn, + toBeUndefined: fn, + toBeNullable: fn, + toMatchTypeOf: fn, + toEqualTypeOf: fn, + toBeCallableWith: fn, + toBeConstructibleWith: fn, + /* eslint-enable mmkal/@typescript-eslint/no-unsafe-assignment */ + extract: exports.expectTypeOf, + exclude: exports.expectTypeOf, + toHaveProperty: exports.expectTypeOf, + parameter: exports.expectTypeOf, + }; + const getterProperties = nonFunctionProperties; + getterProperties.forEach((prop) => Object.defineProperty(obj, prop, { get: () => (0, exports.expectTypeOf)({}) })); + return obj; + }; + exports.expectTypeOf = expectTypeOf; +} (dist)); + +const noop = () => { +}; +const assertType = noop; + +var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + suite: suite, + test: test, + describe: describe, + it: it, + bench: bench, + runOnce: runOnce, + isFirstRun: isFirstRun, + beforeAll: beforeAll, + afterAll: afterAll, + beforeEach: beforeEach, + afterEach: afterEach, + onTestFailed: onTestFailed, + withCallback: withCallback, + assert: assert, + should: should, + createExpect: createExpect, + chai: chai, + expect: globalExpect, + vitest: vitest, + vi: vi, + getRunningMode: getRunningMode, + isWatchMode: isWatchMode, + expectTypeOf: dist.expectTypeOf, + assertType: assertType +}); + +export { afterAll as a, beforeAll as b, beforeEach as c, afterEach as d, dist as e, assertType as f, runOnce as g, isFirstRun as h, index as i, vitest as j, getRunningMode as k, isWatchMode as l, onTestFailed as o, resetRunOnceCounter as r, setCurrentTest as s, vi as v, withCallback as w }; diff --git a/node_modules/vitest/dist/chunk-utils-source-map.60562959.js b/node_modules/vitest/dist/chunk-utils-source-map.60562959.js new file mode 100644 index 0000000..a2ff644 --- /dev/null +++ b/node_modules/vitest/dist/chunk-utils-source-map.60562959.js @@ -0,0 +1,408 @@ +import { d as ansiStyles, e as eastAsianWidth } from './chunk-utils-timers.52534f96.js'; +import { b as resolve } from './chunk-utils-env.b861e3a0.js'; +import { j as notNullish } from './chunk-mock-date.a1c85759.js'; + +/* eslint-disable yoda */ + +function isFullwidthCodePoint(codePoint) { + if (!Number.isInteger(codePoint)) { + return false; + } + + // Code points are derived from: + // https://unicode.org/Public/UNIDATA/EastAsianWidth.txt + return codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ); +} + +const astralRegex = /^[\uD800-\uDBFF][\uDC00-\uDFFF]$/; + +const ESCAPES = [ + '\u001B', + '\u009B' +]; + +const wrapAnsi = code => `${ESCAPES[0]}[${code}m`; + +const checkAnsi = (ansiCodes, isEscapes, endAnsiCode) => { + let output = []; + ansiCodes = [...ansiCodes]; + + for (let ansiCode of ansiCodes) { + const ansiCodeOrigin = ansiCode; + if (ansiCode.includes(';')) { + ansiCode = ansiCode.split(';')[0][0] + '0'; + } + + const item = ansiStyles.codes.get(Number.parseInt(ansiCode, 10)); + if (item) { + const indexEscape = ansiCodes.indexOf(item.toString()); + if (indexEscape === -1) { + output.push(wrapAnsi(isEscapes ? item : ansiCodeOrigin)); + } else { + ansiCodes.splice(indexEscape, 1); + } + } else if (isEscapes) { + output.push(wrapAnsi(0)); + break; + } else { + output.push(wrapAnsi(ansiCodeOrigin)); + } + } + + if (isEscapes) { + output = output.filter((element, index) => output.indexOf(element) === index); + + if (endAnsiCode !== undefined) { + const fistEscapeCode = wrapAnsi(ansiStyles.codes.get(Number.parseInt(endAnsiCode, 10))); + // TODO: Remove the use of `.reduce` here. + // eslint-disable-next-line unicorn/no-array-reduce + output = output.reduce((current, next) => next === fistEscapeCode ? [next, ...current] : [...current, next], []); + } + } + + return output.join(''); +}; + +function sliceAnsi(string, begin, end) { + const characters = [...string]; + const ansiCodes = []; + + let stringEnd = typeof end === 'number' ? end : characters.length; + let isInsideEscape = false; + let ansiCode; + let visible = 0; + let output = ''; + + for (const [index, character] of characters.entries()) { + let leftEscape = false; + + if (ESCAPES.includes(character)) { + const code = /\d[^m]*/.exec(string.slice(index, index + 18)); + ansiCode = code && code.length > 0 ? code[0] : undefined; + + if (visible < stringEnd) { + isInsideEscape = true; + + if (ansiCode !== undefined) { + ansiCodes.push(ansiCode); + } + } + } else if (isInsideEscape && character === 'm') { + isInsideEscape = false; + leftEscape = true; + } + + if (!isInsideEscape && !leftEscape) { + visible++; + } + + if (!astralRegex.test(character) && isFullwidthCodePoint(character.codePointAt())) { + visible++; + + if (typeof end !== 'number') { + stringEnd++; + } + } + + if (visible > begin && visible <= stringEnd) { + output += character; + } else if (visible === begin && !isInsideEscape && ansiCode !== undefined) { + output = checkAnsi(ansiCodes); + } else if (visible >= stringEnd) { + output += checkAnsi(ansiCodes, true, ansiCode); + break; + } + } + + return output; +} + +function ansiRegex({onlyFirst = false} = {}) { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +} + +function stripAnsi(string) { + if (typeof string !== 'string') { + throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); + } + + return string.replace(ansiRegex(), ''); +} + +var emojiRegex = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; + +function stringWidth(string, options = {}) { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + options = { + ambiguousIsNarrow: true, + ...options + }; + + string = stripAnsi(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex(), ' '); + + const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2; + let width = 0; + + for (const character of string) { + const codePoint = character.codePointAt(0); + + // Ignore control characters + if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (codePoint >= 0x300 && codePoint <= 0x36F) { + continue; + } + + const code = eastAsianWidth.eastAsianWidth(character); + switch (code) { + case 'F': + case 'W': + width += 2; + break; + case 'A': + width += ambiguousCharacterWidth; + break; + default: + width += 1; + } + } + + return width; +} + +function getIndexOfNearestSpace(string, wantedIndex, shouldSearchRight) { + if (string.charAt(wantedIndex) === ' ') { + return wantedIndex; + } + + for (let index = 1; index <= 3; index++) { + if (shouldSearchRight) { + if (string.charAt(wantedIndex + index) === ' ') { + return wantedIndex + index; + } + } else if (string.charAt(wantedIndex - index) === ' ') { + return wantedIndex - index; + } + } + + return wantedIndex; +} + +function cliTruncate(text, columns, options) { + options = { + position: 'end', + preferTruncationOnSpace: false, + truncationCharacter: '…', + ...options, + }; + + const {position, space, preferTruncationOnSpace} = options; + let {truncationCharacter} = options; + + if (typeof text !== 'string') { + throw new TypeError(`Expected \`input\` to be a string, got ${typeof text}`); + } + + if (typeof columns !== 'number') { + throw new TypeError(`Expected \`columns\` to be a number, got ${typeof columns}`); + } + + if (columns < 1) { + return ''; + } + + if (columns === 1) { + return truncationCharacter; + } + + const length = stringWidth(text); + + if (length <= columns) { + return text; + } + + if (position === 'start') { + if (preferTruncationOnSpace) { + const nearestSpace = getIndexOfNearestSpace(text, length - columns + 1, true); + return truncationCharacter + sliceAnsi(text, nearestSpace, length).trim(); + } + + if (space === true) { + truncationCharacter += ' '; + } + + return truncationCharacter + sliceAnsi(text, length - columns + stringWidth(truncationCharacter), length); + } + + if (position === 'middle') { + if (space === true) { + truncationCharacter = ` ${truncationCharacter} `; + } + + const half = Math.floor(columns / 2); + + if (preferTruncationOnSpace) { + const spaceNearFirstBreakPoint = getIndexOfNearestSpace(text, half); + const spaceNearSecondBreakPoint = getIndexOfNearestSpace(text, length - (columns - half) + 1, true); + return sliceAnsi(text, 0, spaceNearFirstBreakPoint) + truncationCharacter + sliceAnsi(text, spaceNearSecondBreakPoint, length).trim(); + } + + return ( + sliceAnsi(text, 0, half) + + truncationCharacter + + sliceAnsi(text, length - (columns - half) + stringWidth(truncationCharacter), length) + ); + } + + if (position === 'end') { + if (preferTruncationOnSpace) { + const nearestSpace = getIndexOfNearestSpace(text, columns - 1); + return sliceAnsi(text, 0, nearestSpace) + truncationCharacter; + } + + if (space === true) { + truncationCharacter = ` ${truncationCharacter}`; + } + + return sliceAnsi(text, 0, columns - stringWidth(truncationCharacter)) + truncationCharacter; + } + + throw new Error(`Expected \`options.position\` to be either \`start\`, \`middle\` or \`end\`, got ${position}`); +} + +const lineSplitRE = /\r?\n/; +const stackIgnorePatterns = [ + "node:internal", + "/vitest/dist/", + "/vitest/src/", + "/vite-node/dist/", + "/vite-node/src/", + "/node_modules/chai/", + "/node_modules/tinypool/", + "/node_modules/tinyspy/" +]; +function extractLocation(urlLike) { + if (!urlLike.includes(":")) + return [urlLike]; + const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; + const parts = regExp.exec(urlLike.replace(/[()]/g, "")); + if (!parts) + return [urlLike]; + return [parts[1], parts[2] || void 0, parts[3] || void 0]; +} +function parseSingleStack(raw) { + let line = raw.trim(); + if (line.includes("(eval ")) + line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, ""); + let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, ""); + const location = sanitizedLine.match(/ (\(.+\)$)/); + sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; + const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); + let method = location && sanitizedLine || ""; + let file = url && ["eval", ""].includes(url) ? void 0 : url; + if (!file || !lineNumber || !columnNumber) + return null; + if (method.startsWith("async ")) + method = method.slice(6); + if (file.startsWith("file://")) + file = file.slice(7); + file = resolve(file); + return { + method, + file, + line: parseInt(lineNumber), + column: parseInt(columnNumber) + }; +} +function parseStacktrace(e, full = false) { + if (!e) + return []; + if (e.stacks) + return e.stacks; + const stackStr = e.stack || e.stackStr || ""; + const stackFrames = stackStr.split("\n").map((raw) => { + const stack = parseSingleStack(raw); + if (!stack || !full && stackIgnorePatterns.some((p) => stack.file.includes(p))) + return null; + return stack; + }).filter(notNullish); + e.stacks = stackFrames; + return stackFrames; +} +function positionToOffset(source, lineNumber, columnNumber) { + const lines = source.split(lineSplitRE); + let start = 0; + if (lineNumber > lines.length) + return source.length; + for (let i = 0; i < lineNumber - 1; i++) + start += lines[i].length + 1; + return start + columnNumber; +} +function offsetToLineNumber(source, offset) { + if (offset > source.length) { + throw new Error( + `offset is longer than source length! offset ${offset} > length ${source.length}` + ); + } + const lines = source.split(lineSplitRE); + let counted = 0; + let line = 0; + for (; line < lines.length; line++) { + const lineLength = lines[line].length + 1; + if (counted + lineLength >= offset) + break; + counted += lineLength; + } + return line + 1; +} + +export { positionToOffset as a, parseStacktrace as b, cliTruncate as c, stringWidth as d, sliceAnsi as e, lineSplitRE as l, offsetToLineNumber as o, parseSingleStack as p, stripAnsi as s }; diff --git a/node_modules/vitest/dist/chunk-utils-timers.52534f96.js b/node_modules/vitest/dist/chunk-utils-timers.52534f96.js new file mode 100644 index 0000000..8da36c9 --- /dev/null +++ b/node_modules/vitest/dist/chunk-utils-timers.52534f96.js @@ -0,0 +1,3573 @@ +import 'picocolors'; + +const { + setTimeout: safeSetTimeout, + setInterval: safeSetInterval, + clearInterval: safeClearInterval, + clearTimeout: safeClearTimeout +} = globalThis; + +function Diff() {} +Diff.prototype = { + diff: function diff(oldString, newString) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + + if (options.maxEditLength) { + maxEditLength = Math.min(maxEditLength, options.maxEditLength); + } + + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = void 0; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced, or until the edit length exceeds options.maxEditLength (if given), + // in which case it will return undefined. + + + if (callback) { + (function exec() { + setTimeout(function () { + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return value.split(''); + }, + join: function join(chars) { + return chars.join(''); + } +}; + +function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; +} + +function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; +} + +// +// Ranges and exceptions: +// Latin-1 Supplement, 0080–00FF +// - U+00D7 × Multiplication sign +// - U+00F7 ÷ Division sign +// Latin Extended-A, 0100–017F +// Latin Extended-B, 0180–024F +// IPA Extensions, 0250–02AF +// Spacing Modifier Letters, 02B0–02FF +// - U+02C7 ˇ ˇ Caron +// - U+02D8 ˘ ˘ Breve +// - U+02D9 ˙ ˙ Dot Above +// - U+02DA ˚ ˚ Ring Above +// - U+02DB ˛ ˛ Ogonek +// - U+02DC ˜ ˜ Small Tilde +// - U+02DD ˝ ˝ Double Acute Accent +// Latin Extended Additional, 1E00–1EFF + +var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; +var reWhitespace = /\S/; +var wordDiff = new Diff(); + +wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); +}; + +wordDiff.tokenize = function (value) { + // All whitespace symbols except newline group into one token, each newline - in separate token + var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; +}; + +var lineDiff = new Diff(); + +lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; +}; + +function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); +} + +var sentenceDiff = new Diff(); + +sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; + +var cssDiff = new Diff(); + +cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); +}; + +function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); +} + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); +} + +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); +} + +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 _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."); +} + +var objectPrototypeToString = Object.prototype.toString; +var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a +// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + +jsonDiff.useLongestToken = true; +jsonDiff.tokenize = lineDiff.tokenize; + +jsonDiff.castInput = function (value) { + var _this$options = this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { + return typeof v === 'undefined' ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); +}; + +jsonDiff.equals = function (left, right) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); +}; +// object that is already on the "stack" of items being processed. Accepts an optional replacer + +function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if (_typeof(obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; +} + +var arrayDiff = new Diff(); + +arrayDiff.tokenize = function (value) { + return value.slice(); +}; + +arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; +}; + +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = diffLines(oldStr, newStr, options); + + if (!diff) { + return; + } + + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + var _loop = function _loop(i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + var _curRange; + + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + var _curRange2; + + // Overlapping + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; + + // end the range and output + var contextSize = Math.min(lines.length, options.context); + + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + // however, if the old file is empty, do not output the no-nl line + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + _loop(i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; +} +function formatPatch(diff) { + var ret = []; + + if (diff.oldFileName == diff.newFileName) { + ret.push('Index: ' + diff.oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, + // the first number is one lower than one would expect. + // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 + + if (hunk.oldLines === 0) { + hunk.oldStart -= 1; + } + + if (hunk.newLines === 0) { + hunk.newStart -= 1; + } + + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; +} +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); +} +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} + +const ANSI_BACKGROUND_OFFSET = 10; + +const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; + +const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; + +const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; + +const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + gray: [90, 39], // Alias of `blackBright` + grey: [90, 39], // Alias of `blackBright` + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39], + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgGray: [100, 49], // Alias of `bgBlackBright` + bgGrey: [100, 49], // Alias of `bgBlackBright` + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49], + }, +}; + +Object.keys(styles.modifier); +const foregroundColorNames = Object.keys(styles.color); +const backgroundColorNames = Object.keys(styles.bgColor); +[...foregroundColorNames, ...backgroundColorNames]; + +function assembleStyles() { + const codes = new Map(); + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m`, + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false, + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false, + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = wrapAnsi16(); + styles.color.ansi256 = wrapAnsi256(); + styles.color.ansi16m = wrapAnsi16m(); + styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + + // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js + Object.defineProperties(styles, { + rgbToAnsi256: { + value: (red, green, blue) => { + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + + if (red > 248) { + return 231; + } + + return Math.round(((red - 8) / 247) * 24) + 232; + } + + return 16 + + (36 * Math.round(red / 255 * 5)) + + (6 * Math.round(green / 255 * 5)) + + Math.round(blue / 255 * 5); + }, + enumerable: false, + }, + hexToRgb: { + value: hex => { + const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + + let [colorString] = matches; + + if (colorString.length === 3) { + colorString = [...colorString].map(character => character + character).join(''); + } + + const integer = Number.parseInt(colorString, 16); + + return [ + /* eslint-disable no-bitwise */ + (integer >> 16) & 0xFF, + (integer >> 8) & 0xFF, + integer & 0xFF, + /* eslint-enable no-bitwise */ + ]; + }, + enumerable: false, + }, + hexToAnsi256: { + value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), + enumerable: false, + }, + ansi256ToAnsi: { + value: code => { + if (code < 8) { + return 30 + code; + } + + if (code < 16) { + return 90 + (code - 8); + } + + let red; + let green; + let blue; + + if (code >= 232) { + red = (((code - 232) * 10) + 8) / 255; + green = red; + blue = red; + } else { + code -= 16; + + const remainder = code % 36; + + red = Math.floor(code / 36) / 5; + green = Math.floor(remainder / 6) / 5; + blue = (remainder % 6) / 5; + } + + const value = Math.max(red, green, blue) * 2; + + if (value === 0) { + return 30; + } + + // eslint-disable-next-line no-bitwise + let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); + + if (value === 2) { + result += 60; + } + + return result; + }, + enumerable: false, + }, + rgbToAnsi: { + value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), + enumerable: false, + }, + hexToAnsi: { + value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), + enumerable: false, + }, + }); + + return styles; +} + +const ansiStyles$1 = assembleStyles(); + +var eastasianwidth = {exports: {}}; + +(function (module) { + var eaw = {}; + + { + module.exports = eaw; + } + + eaw.eastAsianWidth = function(character) { + var x = character.charCodeAt(0); + var y = (character.length == 2) ? character.charCodeAt(1) : 0; + var codePoint = x; + if ((0xD800 <= x && x <= 0xDBFF) && (0xDC00 <= y && y <= 0xDFFF)) { + x &= 0x3FF; + y &= 0x3FF; + codePoint = (x << 10) | y; + codePoint += 0x10000; + } + + if ((0x3000 == codePoint) || + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6)) { + return 'F'; + } + if ((0x20A9 == codePoint) || + (0xFF61 <= codePoint && codePoint <= 0xFFBE) || + (0xFFC2 <= codePoint && codePoint <= 0xFFC7) || + (0xFFCA <= codePoint && codePoint <= 0xFFCF) || + (0xFFD2 <= codePoint && codePoint <= 0xFFD7) || + (0xFFDA <= codePoint && codePoint <= 0xFFDC) || + (0xFFE8 <= codePoint && codePoint <= 0xFFEE)) { + return 'H'; + } + if ((0x1100 <= codePoint && codePoint <= 0x115F) || + (0x11A3 <= codePoint && codePoint <= 0x11A7) || + (0x11FA <= codePoint && codePoint <= 0x11FF) || + (0x2329 <= codePoint && codePoint <= 0x232A) || + (0x2E80 <= codePoint && codePoint <= 0x2E99) || + (0x2E9B <= codePoint && codePoint <= 0x2EF3) || + (0x2F00 <= codePoint && codePoint <= 0x2FD5) || + (0x2FF0 <= codePoint && codePoint <= 0x2FFB) || + (0x3001 <= codePoint && codePoint <= 0x303E) || + (0x3041 <= codePoint && codePoint <= 0x3096) || + (0x3099 <= codePoint && codePoint <= 0x30FF) || + (0x3105 <= codePoint && codePoint <= 0x312D) || + (0x3131 <= codePoint && codePoint <= 0x318E) || + (0x3190 <= codePoint && codePoint <= 0x31BA) || + (0x31C0 <= codePoint && codePoint <= 0x31E3) || + (0x31F0 <= codePoint && codePoint <= 0x321E) || + (0x3220 <= codePoint && codePoint <= 0x3247) || + (0x3250 <= codePoint && codePoint <= 0x32FE) || + (0x3300 <= codePoint && codePoint <= 0x4DBF) || + (0x4E00 <= codePoint && codePoint <= 0xA48C) || + (0xA490 <= codePoint && codePoint <= 0xA4C6) || + (0xA960 <= codePoint && codePoint <= 0xA97C) || + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + (0xD7B0 <= codePoint && codePoint <= 0xD7C6) || + (0xD7CB <= codePoint && codePoint <= 0xD7FB) || + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + (0xFE30 <= codePoint && codePoint <= 0xFE52) || + (0xFE54 <= codePoint && codePoint <= 0xFE66) || + (0xFE68 <= codePoint && codePoint <= 0xFE6B) || + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + (0x1F200 <= codePoint && codePoint <= 0x1F202) || + (0x1F210 <= codePoint && codePoint <= 0x1F23A) || + (0x1F240 <= codePoint && codePoint <= 0x1F248) || + (0x1F250 <= codePoint && codePoint <= 0x1F251) || + (0x20000 <= codePoint && codePoint <= 0x2F73F) || + (0x2B740 <= codePoint && codePoint <= 0x2FFFD) || + (0x30000 <= codePoint && codePoint <= 0x3FFFD)) { + return 'W'; + } + if ((0x0020 <= codePoint && codePoint <= 0x007E) || + (0x00A2 <= codePoint && codePoint <= 0x00A3) || + (0x00A5 <= codePoint && codePoint <= 0x00A6) || + (0x00AC == codePoint) || + (0x00AF == codePoint) || + (0x27E6 <= codePoint && codePoint <= 0x27ED) || + (0x2985 <= codePoint && codePoint <= 0x2986)) { + return 'Na'; + } + if ((0x00A1 == codePoint) || + (0x00A4 == codePoint) || + (0x00A7 <= codePoint && codePoint <= 0x00A8) || + (0x00AA == codePoint) || + (0x00AD <= codePoint && codePoint <= 0x00AE) || + (0x00B0 <= codePoint && codePoint <= 0x00B4) || + (0x00B6 <= codePoint && codePoint <= 0x00BA) || + (0x00BC <= codePoint && codePoint <= 0x00BF) || + (0x00C6 == codePoint) || + (0x00D0 == codePoint) || + (0x00D7 <= codePoint && codePoint <= 0x00D8) || + (0x00DE <= codePoint && codePoint <= 0x00E1) || + (0x00E6 == codePoint) || + (0x00E8 <= codePoint && codePoint <= 0x00EA) || + (0x00EC <= codePoint && codePoint <= 0x00ED) || + (0x00F0 == codePoint) || + (0x00F2 <= codePoint && codePoint <= 0x00F3) || + (0x00F7 <= codePoint && codePoint <= 0x00FA) || + (0x00FC == codePoint) || + (0x00FE == codePoint) || + (0x0101 == codePoint) || + (0x0111 == codePoint) || + (0x0113 == codePoint) || + (0x011B == codePoint) || + (0x0126 <= codePoint && codePoint <= 0x0127) || + (0x012B == codePoint) || + (0x0131 <= codePoint && codePoint <= 0x0133) || + (0x0138 == codePoint) || + (0x013F <= codePoint && codePoint <= 0x0142) || + (0x0144 == codePoint) || + (0x0148 <= codePoint && codePoint <= 0x014B) || + (0x014D == codePoint) || + (0x0152 <= codePoint && codePoint <= 0x0153) || + (0x0166 <= codePoint && codePoint <= 0x0167) || + (0x016B == codePoint) || + (0x01CE == codePoint) || + (0x01D0 == codePoint) || + (0x01D2 == codePoint) || + (0x01D4 == codePoint) || + (0x01D6 == codePoint) || + (0x01D8 == codePoint) || + (0x01DA == codePoint) || + (0x01DC == codePoint) || + (0x0251 == codePoint) || + (0x0261 == codePoint) || + (0x02C4 == codePoint) || + (0x02C7 == codePoint) || + (0x02C9 <= codePoint && codePoint <= 0x02CB) || + (0x02CD == codePoint) || + (0x02D0 == codePoint) || + (0x02D8 <= codePoint && codePoint <= 0x02DB) || + (0x02DD == codePoint) || + (0x02DF == codePoint) || + (0x0300 <= codePoint && codePoint <= 0x036F) || + (0x0391 <= codePoint && codePoint <= 0x03A1) || + (0x03A3 <= codePoint && codePoint <= 0x03A9) || + (0x03B1 <= codePoint && codePoint <= 0x03C1) || + (0x03C3 <= codePoint && codePoint <= 0x03C9) || + (0x0401 == codePoint) || + (0x0410 <= codePoint && codePoint <= 0x044F) || + (0x0451 == codePoint) || + (0x2010 == codePoint) || + (0x2013 <= codePoint && codePoint <= 0x2016) || + (0x2018 <= codePoint && codePoint <= 0x2019) || + (0x201C <= codePoint && codePoint <= 0x201D) || + (0x2020 <= codePoint && codePoint <= 0x2022) || + (0x2024 <= codePoint && codePoint <= 0x2027) || + (0x2030 == codePoint) || + (0x2032 <= codePoint && codePoint <= 0x2033) || + (0x2035 == codePoint) || + (0x203B == codePoint) || + (0x203E == codePoint) || + (0x2074 == codePoint) || + (0x207F == codePoint) || + (0x2081 <= codePoint && codePoint <= 0x2084) || + (0x20AC == codePoint) || + (0x2103 == codePoint) || + (0x2105 == codePoint) || + (0x2109 == codePoint) || + (0x2113 == codePoint) || + (0x2116 == codePoint) || + (0x2121 <= codePoint && codePoint <= 0x2122) || + (0x2126 == codePoint) || + (0x212B == codePoint) || + (0x2153 <= codePoint && codePoint <= 0x2154) || + (0x215B <= codePoint && codePoint <= 0x215E) || + (0x2160 <= codePoint && codePoint <= 0x216B) || + (0x2170 <= codePoint && codePoint <= 0x2179) || + (0x2189 == codePoint) || + (0x2190 <= codePoint && codePoint <= 0x2199) || + (0x21B8 <= codePoint && codePoint <= 0x21B9) || + (0x21D2 == codePoint) || + (0x21D4 == codePoint) || + (0x21E7 == codePoint) || + (0x2200 == codePoint) || + (0x2202 <= codePoint && codePoint <= 0x2203) || + (0x2207 <= codePoint && codePoint <= 0x2208) || + (0x220B == codePoint) || + (0x220F == codePoint) || + (0x2211 == codePoint) || + (0x2215 == codePoint) || + (0x221A == codePoint) || + (0x221D <= codePoint && codePoint <= 0x2220) || + (0x2223 == codePoint) || + (0x2225 == codePoint) || + (0x2227 <= codePoint && codePoint <= 0x222C) || + (0x222E == codePoint) || + (0x2234 <= codePoint && codePoint <= 0x2237) || + (0x223C <= codePoint && codePoint <= 0x223D) || + (0x2248 == codePoint) || + (0x224C == codePoint) || + (0x2252 == codePoint) || + (0x2260 <= codePoint && codePoint <= 0x2261) || + (0x2264 <= codePoint && codePoint <= 0x2267) || + (0x226A <= codePoint && codePoint <= 0x226B) || + (0x226E <= codePoint && codePoint <= 0x226F) || + (0x2282 <= codePoint && codePoint <= 0x2283) || + (0x2286 <= codePoint && codePoint <= 0x2287) || + (0x2295 == codePoint) || + (0x2299 == codePoint) || + (0x22A5 == codePoint) || + (0x22BF == codePoint) || + (0x2312 == codePoint) || + (0x2460 <= codePoint && codePoint <= 0x24E9) || + (0x24EB <= codePoint && codePoint <= 0x254B) || + (0x2550 <= codePoint && codePoint <= 0x2573) || + (0x2580 <= codePoint && codePoint <= 0x258F) || + (0x2592 <= codePoint && codePoint <= 0x2595) || + (0x25A0 <= codePoint && codePoint <= 0x25A1) || + (0x25A3 <= codePoint && codePoint <= 0x25A9) || + (0x25B2 <= codePoint && codePoint <= 0x25B3) || + (0x25B6 <= codePoint && codePoint <= 0x25B7) || + (0x25BC <= codePoint && codePoint <= 0x25BD) || + (0x25C0 <= codePoint && codePoint <= 0x25C1) || + (0x25C6 <= codePoint && codePoint <= 0x25C8) || + (0x25CB == codePoint) || + (0x25CE <= codePoint && codePoint <= 0x25D1) || + (0x25E2 <= codePoint && codePoint <= 0x25E5) || + (0x25EF == codePoint) || + (0x2605 <= codePoint && codePoint <= 0x2606) || + (0x2609 == codePoint) || + (0x260E <= codePoint && codePoint <= 0x260F) || + (0x2614 <= codePoint && codePoint <= 0x2615) || + (0x261C == codePoint) || + (0x261E == codePoint) || + (0x2640 == codePoint) || + (0x2642 == codePoint) || + (0x2660 <= codePoint && codePoint <= 0x2661) || + (0x2663 <= codePoint && codePoint <= 0x2665) || + (0x2667 <= codePoint && codePoint <= 0x266A) || + (0x266C <= codePoint && codePoint <= 0x266D) || + (0x266F == codePoint) || + (0x269E <= codePoint && codePoint <= 0x269F) || + (0x26BE <= codePoint && codePoint <= 0x26BF) || + (0x26C4 <= codePoint && codePoint <= 0x26CD) || + (0x26CF <= codePoint && codePoint <= 0x26E1) || + (0x26E3 == codePoint) || + (0x26E8 <= codePoint && codePoint <= 0x26FF) || + (0x273D == codePoint) || + (0x2757 == codePoint) || + (0x2776 <= codePoint && codePoint <= 0x277F) || + (0x2B55 <= codePoint && codePoint <= 0x2B59) || + (0x3248 <= codePoint && codePoint <= 0x324F) || + (0xE000 <= codePoint && codePoint <= 0xF8FF) || + (0xFE00 <= codePoint && codePoint <= 0xFE0F) || + (0xFFFD == codePoint) || + (0x1F100 <= codePoint && codePoint <= 0x1F10A) || + (0x1F110 <= codePoint && codePoint <= 0x1F12D) || + (0x1F130 <= codePoint && codePoint <= 0x1F169) || + (0x1F170 <= codePoint && codePoint <= 0x1F19A) || + (0xE0100 <= codePoint && codePoint <= 0xE01EF) || + (0xF0000 <= codePoint && codePoint <= 0xFFFFD) || + (0x100000 <= codePoint && codePoint <= 0x10FFFD)) { + return 'A'; + } + + return 'N'; + }; + + eaw.characterLength = function(character) { + var code = this.eastAsianWidth(character); + if (code == 'F' || code == 'W' || code == 'A') { + return 2; + } else { + return 1; + } + }; + + // Split a string considering surrogate-pairs. + function stringToArray(string) { + return string.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || []; + } + + eaw.length = function(string) { + var characters = stringToArray(string); + var len = 0; + for (var i = 0; i < characters.length; i++) { + len = len + this.characterLength(characters[i]); + } + return len; + }; + + eaw.slice = function(text, start, end) { + textLen = eaw.length(text); + start = start ? start : 0; + end = end ? end : 1; + if (start < 0) { + start = textLen + start; + } + if (end < 0) { + end = textLen + end; + } + var result = ''; + var eawLen = 0; + var chars = stringToArray(text); + for (var i = 0; i < chars.length; i++) { + var char = chars[i]; + var charLen = eaw.length(char); + if (eawLen >= start - (charLen == 2 ? 1 : 0)) { + if (eawLen + charLen <= end) { + result += char; + } else { + break; + } + } + eawLen += charLen; + } + return result; + }; +} (eastasianwidth)); + +var eastAsianWidth = eastasianwidth.exports; + +var build = {}; + +var ansiStyles = {exports: {}}; + +(function (module) { + + const ANSI_BACKGROUND_OFFSET = 10; + + const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; + + const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi256 = wrapAnsi256(); + styles.color.ansi16m = wrapAnsi16m(); + styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + + // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js + Object.defineProperties(styles, { + rgbToAnsi256: { + value: (red, green, blue) => { + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + + if (red > 248) { + return 231; + } + + return Math.round(((red - 8) / 247) * 24) + 232; + } + + return 16 + + (36 * Math.round(red / 255 * 5)) + + (6 * Math.round(green / 255 * 5)) + + Math.round(blue / 255 * 5); + }, + enumerable: false + }, + hexToRgb: { + value: hex => { + const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + + let {colorString} = matches.groups; + + if (colorString.length === 3) { + colorString = colorString.split('').map(character => character + character).join(''); + } + + const integer = Number.parseInt(colorString, 16); + + return [ + (integer >> 16) & 0xFF, + (integer >> 8) & 0xFF, + integer & 0xFF + ]; + }, + enumerable: false + }, + hexToAnsi256: { + value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), + enumerable: false + } + }); + + return styles; + } + + // Make the export immutable + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); +} (ansiStyles)); + +var collections = {}; + +Object.defineProperty(collections, '__esModule', { + value: true +}); +collections.printIteratorEntries = printIteratorEntries; +collections.printIteratorValues = printIteratorValues; +collections.printListItems = printListItems; +collections.printObjectProperties = printObjectProperties; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +const getKeysOfEnumerableProperties = (object, compareKeys) => { + const keys = Object.keys(object).sort(compareKeys); + + if (Object.getOwnPropertySymbols) { + Object.getOwnPropertySymbols(object).forEach(symbol => { + if (Object.getOwnPropertyDescriptor(object, symbol).enumerable) { + keys.push(symbol); + } + }); + } + + return keys; +}; +/** + * Return entries (for example, of a map) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ + +function printIteratorEntries( + iterator, + config, + indentation, + depth, + refs, + printer, // Too bad, so sad that separator for ECMAScript Map has been ' => ' + // What a distracting diff if you change a data structure to/from + // ECMAScript Object or Immutable.Map/OrderedMap which use the default. + separator = ': ' +) { + let result = ''; + let current = iterator.next(); + + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + while (!current.done) { + const name = printer( + current.value[0], + config, + indentationNext, + depth, + refs + ); + const value = printer( + current.value[1], + config, + indentationNext, + depth, + refs + ); + result += indentationNext + name + separator + value; + current = iterator.next(); + + if (!current.done) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; +} +/** + * Return values (for example, of a set) + * with spacing, indentation, and comma + * without surrounding punctuation (braces or brackets) + */ + +function printIteratorValues( + iterator, + config, + indentation, + depth, + refs, + printer +) { + let result = ''; + let current = iterator.next(); + + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + while (!current.done) { + result += + indentationNext + + printer(current.value, config, indentationNext, depth, refs); + current = iterator.next(); + + if (!current.done) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; +} +/** + * Return items (for example, of an array) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, brackets) + **/ + +function printListItems(list, config, indentation, depth, refs, printer) { + let result = ''; + + if (list.length) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + for (let i = 0; i < list.length; i++) { + result += indentationNext; + + if (i in list) { + result += printer(list[i], config, indentationNext, depth, refs); + } + + if (i < list.length - 1) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; +} +/** + * Return properties of an object + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ + +function printObjectProperties(val, config, indentation, depth, refs, printer) { + let result = ''; + const keys = getKeysOfEnumerableProperties(val, config.compareKeys); + + if (keys.length) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const name = printer(key, config, indentationNext, depth, refs); + const value = printer(val[key], config, indentationNext, depth, refs); + result += indentationNext + name + ': ' + value; + + if (i < keys.length - 1) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; +} + +var AsymmetricMatcher$1 = {}; + +Object.defineProperty(AsymmetricMatcher$1, '__esModule', { + value: true +}); +AsymmetricMatcher$1.test = AsymmetricMatcher$1.serialize = AsymmetricMatcher$1.default = void 0; + +var _collections$3 = collections; + +var global$1 = (function () { + if (typeof globalThis !== 'undefined') { + return globalThis; + } else if (typeof global$1 !== 'undefined') { + return global$1; + } else if (typeof self !== 'undefined') { + return self; + } else if (typeof window !== 'undefined') { + return window; + } else { + return Function('return this')(); + } +})(); + +var Symbol$2 = global$1['jest-symbol-do-not-touch'] || global$1.Symbol; +const asymmetricMatcher = + typeof Symbol$2 === 'function' && Symbol$2.for + ? Symbol$2.for('jest.asymmetricMatcher') + : 0x1357a5; +const SPACE$2 = ' '; + +const serialize$6 = (val, config, indentation, depth, refs, printer) => { + const stringedValue = val.toString(); + + if ( + stringedValue === 'ArrayContaining' || + stringedValue === 'ArrayNotContaining' + ) { + if (++depth > config.maxDepth) { + return '[' + stringedValue + ']'; + } + + return ( + stringedValue + + SPACE$2 + + '[' + + (0, _collections$3.printListItems)( + val.sample, + config, + indentation, + depth, + refs, + printer + ) + + ']' + ); + } + + if ( + stringedValue === 'ObjectContaining' || + stringedValue === 'ObjectNotContaining' + ) { + if (++depth > config.maxDepth) { + return '[' + stringedValue + ']'; + } + + return ( + stringedValue + + SPACE$2 + + '{' + + (0, _collections$3.printObjectProperties)( + val.sample, + config, + indentation, + depth, + refs, + printer + ) + + '}' + ); + } + + if ( + stringedValue === 'StringMatching' || + stringedValue === 'StringNotMatching' + ) { + return ( + stringedValue + + SPACE$2 + + printer(val.sample, config, indentation, depth, refs) + ); + } + + if ( + stringedValue === 'StringContaining' || + stringedValue === 'StringNotContaining' + ) { + return ( + stringedValue + + SPACE$2 + + printer(val.sample, config, indentation, depth, refs) + ); + } + + return val.toAsymmetricMatcher(); +}; + +AsymmetricMatcher$1.serialize = serialize$6; + +const test$6 = val => val && val.$$typeof === asymmetricMatcher; + +AsymmetricMatcher$1.test = test$6; +const plugin$6 = { + serialize: serialize$6, + test: test$6 +}; +var _default$7 = plugin$6; +AsymmetricMatcher$1.default = _default$7; + +var ConvertAnsi = {}; + +var ansiRegex = ({onlyFirst = false} = {}) => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +}; + +Object.defineProperty(ConvertAnsi, '__esModule', { + value: true +}); +ConvertAnsi.test = ConvertAnsi.serialize = ConvertAnsi.default = void 0; + +var _ansiRegex = _interopRequireDefault$2(ansiRegex); + +var _ansiStyles$1 = _interopRequireDefault$2(ansiStyles.exports); + +function _interopRequireDefault$2(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const toHumanReadableAnsi = text => + text.replace((0, _ansiRegex.default)(), match => { + switch (match) { + case _ansiStyles$1.default.red.close: + case _ansiStyles$1.default.green.close: + case _ansiStyles$1.default.cyan.close: + case _ansiStyles$1.default.gray.close: + case _ansiStyles$1.default.white.close: + case _ansiStyles$1.default.yellow.close: + case _ansiStyles$1.default.bgRed.close: + case _ansiStyles$1.default.bgGreen.close: + case _ansiStyles$1.default.bgYellow.close: + case _ansiStyles$1.default.inverse.close: + case _ansiStyles$1.default.dim.close: + case _ansiStyles$1.default.bold.close: + case _ansiStyles$1.default.reset.open: + case _ansiStyles$1.default.reset.close: + return ''; + + case _ansiStyles$1.default.red.open: + return ''; + + case _ansiStyles$1.default.green.open: + return ''; + + case _ansiStyles$1.default.cyan.open: + return ''; + + case _ansiStyles$1.default.gray.open: + return ''; + + case _ansiStyles$1.default.white.open: + return ''; + + case _ansiStyles$1.default.yellow.open: + return ''; + + case _ansiStyles$1.default.bgRed.open: + return ''; + + case _ansiStyles$1.default.bgGreen.open: + return ''; + + case _ansiStyles$1.default.bgYellow.open: + return ''; + + case _ansiStyles$1.default.inverse.open: + return ''; + + case _ansiStyles$1.default.dim.open: + return ''; + + case _ansiStyles$1.default.bold.open: + return ''; + + default: + return ''; + } + }); + +const test$5 = val => + typeof val === 'string' && !!val.match((0, _ansiRegex.default)()); + +ConvertAnsi.test = test$5; + +const serialize$5 = (val, config, indentation, depth, refs, printer) => + printer(toHumanReadableAnsi(val), config, indentation, depth, refs); + +ConvertAnsi.serialize = serialize$5; +const plugin$5 = { + serialize: serialize$5, + test: test$5 +}; +var _default$6 = plugin$5; +ConvertAnsi.default = _default$6; + +var DOMCollection$1 = {}; + +Object.defineProperty(DOMCollection$1, '__esModule', { + value: true +}); +DOMCollection$1.test = DOMCollection$1.serialize = DOMCollection$1.default = void 0; + +var _collections$2 = collections; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually */ +const SPACE$1 = ' '; +const OBJECT_NAMES = ['DOMStringMap', 'NamedNodeMap']; +const ARRAY_REGEXP = /^(HTML\w*Collection|NodeList)$/; + +const testName = name => + OBJECT_NAMES.indexOf(name) !== -1 || ARRAY_REGEXP.test(name); + +const test$4 = val => + val && + val.constructor && + !!val.constructor.name && + testName(val.constructor.name); + +DOMCollection$1.test = test$4; + +const isNamedNodeMap = collection => + collection.constructor.name === 'NamedNodeMap'; + +const serialize$4 = (collection, config, indentation, depth, refs, printer) => { + const name = collection.constructor.name; + + if (++depth > config.maxDepth) { + return '[' + name + ']'; + } + + return ( + (config.min ? '' : name + SPACE$1) + + (OBJECT_NAMES.indexOf(name) !== -1 + ? '{' + + (0, _collections$2.printObjectProperties)( + isNamedNodeMap(collection) + ? Array.from(collection).reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}) + : {...collection}, + config, + indentation, + depth, + refs, + printer + ) + + '}' + : '[' + + (0, _collections$2.printListItems)( + Array.from(collection), + config, + indentation, + depth, + refs, + printer + ) + + ']') + ); +}; + +DOMCollection$1.serialize = serialize$4; +const plugin$4 = { + serialize: serialize$4, + test: test$4 +}; +var _default$5 = plugin$4; +DOMCollection$1.default = _default$5; + +var DOMElement$1 = {}; + +var markup = {}; + +var escapeHTML$1 = {}; + +Object.defineProperty(escapeHTML$1, '__esModule', { + value: true +}); +escapeHTML$1.default = escapeHTML; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function escapeHTML(str) { + return str.replace(//g, '>'); +} + +Object.defineProperty(markup, '__esModule', { + value: true +}); +markup.printText = + markup.printProps = + markup.printElementAsLeaf = + markup.printElement = + markup.printComment = + markup.printChildren = + void 0; + +var _escapeHTML = _interopRequireDefault$1(escapeHTML$1); + +function _interopRequireDefault$1(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// Return empty string if keys is empty. +const printProps = (keys, props, config, indentation, depth, refs, printer) => { + const indentationNext = indentation + config.indent; + const colors = config.colors; + return keys + .map(key => { + const value = props[key]; + let printed = printer(value, config, indentationNext, depth, refs); + + if (typeof value !== 'string') { + if (printed.indexOf('\n') !== -1) { + printed = + config.spacingOuter + + indentationNext + + printed + + config.spacingOuter + + indentation; + } + + printed = '{' + printed + '}'; + } + + return ( + config.spacingInner + + indentation + + colors.prop.open + + key + + colors.prop.close + + '=' + + colors.value.open + + printed + + colors.value.close + ); + }) + .join(''); +}; // Return empty string if children is empty. + +markup.printProps = printProps; + +const printChildren = (children, config, indentation, depth, refs, printer) => + children + .map( + child => + config.spacingOuter + + indentation + + (typeof child === 'string' + ? printText(child, config) + : printer(child, config, indentation, depth, refs)) + ) + .join(''); + +markup.printChildren = printChildren; + +const printText = (text, config) => { + const contentColor = config.colors.content; + return ( + contentColor.open + (0, _escapeHTML.default)(text) + contentColor.close + ); +}; + +markup.printText = printText; + +const printComment = (comment, config) => { + const commentColor = config.colors.comment; + return ( + commentColor.open + + '' + + commentColor.close + ); +}; // Separate the functions to format props, children, and element, +// so a plugin could override a particular function, if needed. +// Too bad, so sad: the traditional (but unnecessary) space +// in a self-closing tagColor requires a second test of printedProps. + +markup.printComment = printComment; + +const printElement = ( + type, + printedProps, + printedChildren, + config, + indentation +) => { + const tagColor = config.colors.tag; + return ( + tagColor.open + + '<' + + type + + (printedProps && + tagColor.close + + printedProps + + config.spacingOuter + + indentation + + tagColor.open) + + (printedChildren + ? '>' + + tagColor.close + + printedChildren + + config.spacingOuter + + indentation + + tagColor.open + + '' + + tagColor.close + ); +}; + +markup.printElement = printElement; + +const printElementAsLeaf = (type, config) => { + const tagColor = config.colors.tag; + return ( + tagColor.open + + '<' + + type + + tagColor.close + + ' …' + + tagColor.open + + ' />' + + tagColor.close + ); +}; + +markup.printElementAsLeaf = printElementAsLeaf; + +Object.defineProperty(DOMElement$1, '__esModule', { + value: true +}); +DOMElement$1.test = DOMElement$1.serialize = DOMElement$1.default = void 0; + +var _markup$2 = markup; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const ELEMENT_NODE = 1; +const TEXT_NODE = 3; +const COMMENT_NODE = 8; +const FRAGMENT_NODE = 11; +const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; + +const testHasAttribute = val => { + try { + return typeof val.hasAttribute === 'function' && val.hasAttribute('is'); + } catch { + return false; + } +}; + +const testNode = val => { + const constructorName = val.constructor.name; + const {nodeType, tagName} = val; + const isCustomElement = + (typeof tagName === 'string' && tagName.includes('-')) || + testHasAttribute(val); + return ( + (nodeType === ELEMENT_NODE && + (ELEMENT_REGEXP.test(constructorName) || isCustomElement)) || + (nodeType === TEXT_NODE && constructorName === 'Text') || + (nodeType === COMMENT_NODE && constructorName === 'Comment') || + (nodeType === FRAGMENT_NODE && constructorName === 'DocumentFragment') + ); +}; + +const test$3 = val => { + var _val$constructor; + + return ( + (val === null || val === void 0 + ? void 0 + : (_val$constructor = val.constructor) === null || + _val$constructor === void 0 + ? void 0 + : _val$constructor.name) && testNode(val) + ); +}; + +DOMElement$1.test = test$3; + +function nodeIsText(node) { + return node.nodeType === TEXT_NODE; +} + +function nodeIsComment(node) { + return node.nodeType === COMMENT_NODE; +} + +function nodeIsFragment(node) { + return node.nodeType === FRAGMENT_NODE; +} + +const serialize$3 = (node, config, indentation, depth, refs, printer) => { + if (nodeIsText(node)) { + return (0, _markup$2.printText)(node.data, config); + } + + if (nodeIsComment(node)) { + return (0, _markup$2.printComment)(node.data, config); + } + + const type = nodeIsFragment(node) + ? 'DocumentFragment' + : node.tagName.toLowerCase(); + + if (++depth > config.maxDepth) { + return (0, _markup$2.printElementAsLeaf)(type, config); + } + + return (0, _markup$2.printElement)( + type, + (0, _markup$2.printProps)( + nodeIsFragment(node) + ? [] + : Array.from(node.attributes) + .map(attr => attr.name) + .sort(), + nodeIsFragment(node) + ? {} + : Array.from(node.attributes).reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}), + config, + indentation + config.indent, + depth, + refs, + printer + ), + (0, _markup$2.printChildren)( + Array.prototype.slice.call(node.childNodes || node.children), + config, + indentation + config.indent, + depth, + refs, + printer + ), + config, + indentation + ); +}; + +DOMElement$1.serialize = serialize$3; +const plugin$3 = { + serialize: serialize$3, + test: test$3 +}; +var _default$4 = plugin$3; +DOMElement$1.default = _default$4; + +var Immutable$1 = {}; + +Object.defineProperty(Immutable$1, '__esModule', { + value: true +}); +Immutable$1.test = Immutable$1.serialize = Immutable$1.default = void 0; + +var _collections$1 = collections; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// SENTINEL constants are from https://github.com/facebook/immutable-js +const IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; +const IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; +const IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; +const IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; +const IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; +const IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@'; // immutable v4 + +const IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; +const IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; +const IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; + +const getImmutableName = name => 'Immutable.' + name; + +const printAsLeaf = name => '[' + name + ']'; + +const SPACE = ' '; +const LAZY = '…'; // Seq is lazy if it calls a method like filter + +const printImmutableEntries = ( + val, + config, + indentation, + depth, + refs, + printer, + type +) => + ++depth > config.maxDepth + ? printAsLeaf(getImmutableName(type)) + : getImmutableName(type) + + SPACE + + '{' + + (0, _collections$1.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer + ) + + '}'; // Record has an entries method because it is a collection in immutable v3. +// Return an iterator for Immutable Record from version v3 or v4. + +function getRecordEntries(val) { + let i = 0; + return { + next() { + if (i < val._keys.length) { + const key = val._keys[i++]; + return { + done: false, + value: [key, val.get(key)] + }; + } + + return { + done: true, + value: undefined + }; + } + }; +} + +const printImmutableRecord = ( + val, + config, + indentation, + depth, + refs, + printer +) => { + // _name property is defined only for an Immutable Record instance + // which was constructed with a second optional descriptive name arg + const name = getImmutableName(val._name || 'Record'); + return ++depth > config.maxDepth + ? printAsLeaf(name) + : name + + SPACE + + '{' + + (0, _collections$1.printIteratorEntries)( + getRecordEntries(val), + config, + indentation, + depth, + refs, + printer + ) + + '}'; +}; + +const printImmutableSeq = (val, config, indentation, depth, refs, printer) => { + const name = getImmutableName('Seq'); + + if (++depth > config.maxDepth) { + return printAsLeaf(name); + } + + if (val[IS_KEYED_SENTINEL]) { + return ( + name + + SPACE + + '{' + // from Immutable collection of entries or from ECMAScript object + (val._iter || val._object + ? (0, _collections$1.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer + ) + : LAZY) + + '}' + ); + } + + return ( + name + + SPACE + + '[' + + (val._iter || // from Immutable collection of values + val._array || // from ECMAScript array + val._collection || // from ECMAScript collection in immutable v4 + val._iterable // from ECMAScript collection in immutable v3 + ? (0, _collections$1.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + : LAZY) + + ']' + ); +}; + +const printImmutableValues = ( + val, + config, + indentation, + depth, + refs, + printer, + type +) => + ++depth > config.maxDepth + ? printAsLeaf(getImmutableName(type)) + : getImmutableName(type) + + SPACE + + '[' + + (0, _collections$1.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + + ']'; + +const serialize$2 = (val, config, indentation, depth, refs, printer) => { + if (val[IS_MAP_SENTINEL]) { + return printImmutableEntries( + val, + config, + indentation, + depth, + refs, + printer, + val[IS_ORDERED_SENTINEL] ? 'OrderedMap' : 'Map' + ); + } + + if (val[IS_LIST_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + 'List' + ); + } + + if (val[IS_SET_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + val[IS_ORDERED_SENTINEL] ? 'OrderedSet' : 'Set' + ); + } + + if (val[IS_STACK_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + 'Stack' + ); + } + + if (val[IS_SEQ_SENTINEL]) { + return printImmutableSeq(val, config, indentation, depth, refs, printer); + } // For compatibility with immutable v3 and v4, let record be the default. + + return printImmutableRecord(val, config, indentation, depth, refs, printer); +}; // Explicitly comparing sentinel properties to true avoids false positive +// when mock identity-obj-proxy returns the key as the value for any key. + +Immutable$1.serialize = serialize$2; + +const test$2 = val => + val && + (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); + +Immutable$1.test = test$2; +const plugin$2 = { + serialize: serialize$2, + test: test$2 +}; +var _default$3 = plugin$2; +Immutable$1.default = _default$3; + +var ReactElement$1 = {}; + +var reactIs = {exports: {}}; + +var reactIs_production_min = {}; + +/** @license React v17.0.2 + * react-is.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +var hasRequiredReactIs_production_min; + +function requireReactIs_production_min () { + if (hasRequiredReactIs_production_min) return reactIs_production_min; + hasRequiredReactIs_production_min = 1; +var b=60103,c=60106,d=60107,e=60108,f=60114,g=60109,h=60110,k=60112,l=60113,m=60120,n=60115,p=60116,q=60121,r=60122,u=60117,v=60129,w=60131; + if("function"===typeof Symbol&&Symbol.for){var x=Symbol.for;b=x("react.element");c=x("react.portal");d=x("react.fragment");e=x("react.strict_mode");f=x("react.profiler");g=x("react.provider");h=x("react.context");k=x("react.forward_ref");l=x("react.suspense");m=x("react.suspense_list");n=x("react.memo");p=x("react.lazy");q=x("react.block");r=x("react.server.block");u=x("react.fundamental");v=x("react.debug_trace_mode");w=x("react.legacy_hidden");} + function y(a){if("object"===typeof a&&null!==a){var t=a.$$typeof;switch(t){case b:switch(a=a.type,a){case d:case f:case e:case l:case m:return a;default:switch(a=a&&a.$$typeof,a){case h:case k:case p:case n:case g:return a;default:return t}}case c:return t}}}var z=g,A=b,B=k,C=d,D=p,E=n,F=c,G=f,H=e,I=l;reactIs_production_min.ContextConsumer=h;reactIs_production_min.ContextProvider=z;reactIs_production_min.Element=A;reactIs_production_min.ForwardRef=B;reactIs_production_min.Fragment=C;reactIs_production_min.Lazy=D;reactIs_production_min.Memo=E;reactIs_production_min.Portal=F;reactIs_production_min.Profiler=G;reactIs_production_min.StrictMode=H; + reactIs_production_min.Suspense=I;reactIs_production_min.isAsyncMode=function(){return !1};reactIs_production_min.isConcurrentMode=function(){return !1};reactIs_production_min.isContextConsumer=function(a){return y(a)===h};reactIs_production_min.isContextProvider=function(a){return y(a)===g};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===b};reactIs_production_min.isForwardRef=function(a){return y(a)===k};reactIs_production_min.isFragment=function(a){return y(a)===d};reactIs_production_min.isLazy=function(a){return y(a)===p};reactIs_production_min.isMemo=function(a){return y(a)===n}; + reactIs_production_min.isPortal=function(a){return y(a)===c};reactIs_production_min.isProfiler=function(a){return y(a)===f};reactIs_production_min.isStrictMode=function(a){return y(a)===e};reactIs_production_min.isSuspense=function(a){return y(a)===l};reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===d||a===f||a===v||a===e||a===l||a===m||a===w||"object"===typeof a&&null!==a&&(a.$$typeof===p||a.$$typeof===n||a.$$typeof===g||a.$$typeof===h||a.$$typeof===k||a.$$typeof===u||a.$$typeof===q||a[0]===r)?!0:!1}; + reactIs_production_min.typeOf=y; + return reactIs_production_min; +} + +var reactIs_development = {}; + +/** @license React v17.0.2 + * react-is.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +var hasRequiredReactIs_development; + +function requireReactIs_development () { + if (hasRequiredReactIs_development) return reactIs_development; + hasRequiredReactIs_development = 1; + + if (process.env.NODE_ENV !== "production") { + (function() { + + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. If there is no native Symbol + // nor polyfill, then a plain number is used for performance. + var REACT_ELEMENT_TYPE = 0xeac7; + var REACT_PORTAL_TYPE = 0xeaca; + var REACT_FRAGMENT_TYPE = 0xeacb; + var REACT_STRICT_MODE_TYPE = 0xeacc; + var REACT_PROFILER_TYPE = 0xead2; + var REACT_PROVIDER_TYPE = 0xeacd; + var REACT_CONTEXT_TYPE = 0xeace; + var REACT_FORWARD_REF_TYPE = 0xead0; + var REACT_SUSPENSE_TYPE = 0xead1; + var REACT_SUSPENSE_LIST_TYPE = 0xead8; + var REACT_MEMO_TYPE = 0xead3; + var REACT_LAZY_TYPE = 0xead4; + var REACT_BLOCK_TYPE = 0xead9; + var REACT_SERVER_BLOCK_TYPE = 0xeada; + var REACT_FUNDAMENTAL_TYPE = 0xead5; + var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; + var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; + + if (typeof Symbol === 'function' && Symbol.for) { + var symbolFor = Symbol.for; + REACT_ELEMENT_TYPE = symbolFor('react.element'); + REACT_PORTAL_TYPE = symbolFor('react.portal'); + REACT_FRAGMENT_TYPE = symbolFor('react.fragment'); + REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); + REACT_PROFILER_TYPE = symbolFor('react.profiler'); + REACT_PROVIDER_TYPE = symbolFor('react.provider'); + REACT_CONTEXT_TYPE = symbolFor('react.context'); + REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); + REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); + REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); + REACT_MEMO_TYPE = symbolFor('react.memo'); + REACT_LAZY_TYPE = symbolFor('react.lazy'); + REACT_BLOCK_TYPE = symbolFor('react.block'); + REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); + REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); + symbolFor('react.scope'); + symbolFor('react.opaque.id'); + REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); + symbolFor('react.offscreen'); + REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); + } + + // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. + + var enableScopeAPI = false; // Experimental Create Event Handle API. + + function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) { + return true; + } + + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) { + return true; + } + } + + return false; + } + + function typeOf(object) { + if (typeof object === 'object' && object !== null) { + var $$typeof = object.$$typeof; + + switch ($$typeof) { + case REACT_ELEMENT_TYPE: + var type = object.type; + + switch (type) { + case REACT_FRAGMENT_TYPE: + case REACT_PROFILER_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_SUSPENSE_TYPE: + case REACT_SUSPENSE_LIST_TYPE: + return type; + + default: + var $$typeofType = type && type.$$typeof; + + switch ($$typeofType) { + case REACT_CONTEXT_TYPE: + case REACT_FORWARD_REF_TYPE: + case REACT_LAZY_TYPE: + case REACT_MEMO_TYPE: + case REACT_PROVIDER_TYPE: + return $$typeofType; + + default: + return $$typeof; + } + + } + + case REACT_PORTAL_TYPE: + return $$typeof; + } + } + + return undefined; + } + var ContextConsumer = REACT_CONTEXT_TYPE; + var ContextProvider = REACT_PROVIDER_TYPE; + var Element = REACT_ELEMENT_TYPE; + var ForwardRef = REACT_FORWARD_REF_TYPE; + var Fragment = REACT_FRAGMENT_TYPE; + var Lazy = REACT_LAZY_TYPE; + var Memo = REACT_MEMO_TYPE; + var Portal = REACT_PORTAL_TYPE; + var Profiler = REACT_PROFILER_TYPE; + var StrictMode = REACT_STRICT_MODE_TYPE; + var Suspense = REACT_SUSPENSE_TYPE; + var hasWarnedAboutDeprecatedIsAsyncMode = false; + var hasWarnedAboutDeprecatedIsConcurrentMode = false; // AsyncMode should be deprecated + + function isAsyncMode(object) { + { + if (!hasWarnedAboutDeprecatedIsAsyncMode) { + hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); + } + } + + return false; + } + function isConcurrentMode(object) { + { + if (!hasWarnedAboutDeprecatedIsConcurrentMode) { + hasWarnedAboutDeprecatedIsConcurrentMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isConcurrentMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); + } + } + + return false; + } + function isContextConsumer(object) { + return typeOf(object) === REACT_CONTEXT_TYPE; + } + function isContextProvider(object) { + return typeOf(object) === REACT_PROVIDER_TYPE; + } + function isElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + function isForwardRef(object) { + return typeOf(object) === REACT_FORWARD_REF_TYPE; + } + function isFragment(object) { + return typeOf(object) === REACT_FRAGMENT_TYPE; + } + function isLazy(object) { + return typeOf(object) === REACT_LAZY_TYPE; + } + function isMemo(object) { + return typeOf(object) === REACT_MEMO_TYPE; + } + function isPortal(object) { + return typeOf(object) === REACT_PORTAL_TYPE; + } + function isProfiler(object) { + return typeOf(object) === REACT_PROFILER_TYPE; + } + function isStrictMode(object) { + return typeOf(object) === REACT_STRICT_MODE_TYPE; + } + function isSuspense(object) { + return typeOf(object) === REACT_SUSPENSE_TYPE; + } + + reactIs_development.ContextConsumer = ContextConsumer; + reactIs_development.ContextProvider = ContextProvider; + reactIs_development.Element = Element; + reactIs_development.ForwardRef = ForwardRef; + reactIs_development.Fragment = Fragment; + reactIs_development.Lazy = Lazy; + reactIs_development.Memo = Memo; + reactIs_development.Portal = Portal; + reactIs_development.Profiler = Profiler; + reactIs_development.StrictMode = StrictMode; + reactIs_development.Suspense = Suspense; + reactIs_development.isAsyncMode = isAsyncMode; + reactIs_development.isConcurrentMode = isConcurrentMode; + reactIs_development.isContextConsumer = isContextConsumer; + reactIs_development.isContextProvider = isContextProvider; + reactIs_development.isElement = isElement; + reactIs_development.isForwardRef = isForwardRef; + reactIs_development.isFragment = isFragment; + reactIs_development.isLazy = isLazy; + reactIs_development.isMemo = isMemo; + reactIs_development.isPortal = isPortal; + reactIs_development.isProfiler = isProfiler; + reactIs_development.isStrictMode = isStrictMode; + reactIs_development.isSuspense = isSuspense; + reactIs_development.isValidElementType = isValidElementType; + reactIs_development.typeOf = typeOf; + })(); + } + return reactIs_development; +} + +(function (module) { + + if (process.env.NODE_ENV === 'production') { + module.exports = requireReactIs_production_min(); + } else { + module.exports = requireReactIs_development(); + } +} (reactIs)); + +Object.defineProperty(ReactElement$1, '__esModule', { + value: true +}); +ReactElement$1.test = ReactElement$1.serialize = ReactElement$1.default = void 0; + +var ReactIs = _interopRequireWildcard(reactIs.exports); + +var _markup$1 = markup; + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// Given element.props.children, or subtree during recursive traversal, +// return flattened array of children. +const getChildren = (arg, children = []) => { + if (Array.isArray(arg)) { + arg.forEach(item => { + getChildren(item, children); + }); + } else if (arg != null && arg !== false) { + children.push(arg); + } + + return children; +}; + +const getType = element => { + const type = element.type; + + if (typeof type === 'string') { + return type; + } + + if (typeof type === 'function') { + return type.displayName || type.name || 'Unknown'; + } + + if (ReactIs.isFragment(element)) { + return 'React.Fragment'; + } + + if (ReactIs.isSuspense(element)) { + return 'React.Suspense'; + } + + if (typeof type === 'object' && type !== null) { + if (ReactIs.isContextProvider(element)) { + return 'Context.Provider'; + } + + if (ReactIs.isContextConsumer(element)) { + return 'Context.Consumer'; + } + + if (ReactIs.isForwardRef(element)) { + if (type.displayName) { + return type.displayName; + } + + const functionName = type.render.displayName || type.render.name || ''; + return functionName !== '' + ? 'ForwardRef(' + functionName + ')' + : 'ForwardRef'; + } + + if (ReactIs.isMemo(element)) { + const functionName = + type.displayName || type.type.displayName || type.type.name || ''; + return functionName !== '' ? 'Memo(' + functionName + ')' : 'Memo'; + } + } + + return 'UNDEFINED'; +}; + +const getPropKeys$1 = element => { + const {props} = element; + return Object.keys(props) + .filter(key => key !== 'children' && props[key] !== undefined) + .sort(); +}; + +const serialize$1 = (element, config, indentation, depth, refs, printer) => + ++depth > config.maxDepth + ? (0, _markup$1.printElementAsLeaf)(getType(element), config) + : (0, _markup$1.printElement)( + getType(element), + (0, _markup$1.printProps)( + getPropKeys$1(element), + element.props, + config, + indentation + config.indent, + depth, + refs, + printer + ), + (0, _markup$1.printChildren)( + getChildren(element.props.children), + config, + indentation + config.indent, + depth, + refs, + printer + ), + config, + indentation + ); + +ReactElement$1.serialize = serialize$1; + +const test$1 = val => val != null && ReactIs.isElement(val); + +ReactElement$1.test = test$1; +const plugin$1 = { + serialize: serialize$1, + test: test$1 +}; +var _default$2 = plugin$1; +ReactElement$1.default = _default$2; + +var ReactTestComponent$1 = {}; + +Object.defineProperty(ReactTestComponent$1, '__esModule', { + value: true +}); +ReactTestComponent$1.test = ReactTestComponent$1.serialize = ReactTestComponent$1.default = void 0; + +var _markup = markup; + +var global = (function () { + if (typeof globalThis !== 'undefined') { + return globalThis; + } else if (typeof global !== 'undefined') { + return global; + } else if (typeof self !== 'undefined') { + return self; + } else if (typeof window !== 'undefined') { + return window; + } else { + return Function('return this')(); + } +})(); + +var Symbol$1 = global['jest-symbol-do-not-touch'] || global.Symbol; +const testSymbol = + typeof Symbol$1 === 'function' && Symbol$1.for + ? Symbol$1.for('react.test.json') + : 0xea71357; + +const getPropKeys = object => { + const {props} = object; + return props + ? Object.keys(props) + .filter(key => props[key] !== undefined) + .sort() + : []; +}; + +const serialize = (object, config, indentation, depth, refs, printer) => + ++depth > config.maxDepth + ? (0, _markup.printElementAsLeaf)(object.type, config) + : (0, _markup.printElement)( + object.type, + object.props + ? (0, _markup.printProps)( + getPropKeys(object), + object.props, + config, + indentation + config.indent, + depth, + refs, + printer + ) + : '', + object.children + ? (0, _markup.printChildren)( + object.children, + config, + indentation + config.indent, + depth, + refs, + printer + ) + : '', + config, + indentation + ); + +ReactTestComponent$1.serialize = serialize; + +const test = val => val && val.$$typeof === testSymbol; + +ReactTestComponent$1.test = test; +const plugin = { + serialize, + test +}; +var _default$1 = plugin; +ReactTestComponent$1.default = _default$1; + +Object.defineProperty(build, '__esModule', { + value: true +}); +build.default = build.DEFAULT_OPTIONS = void 0; +var format_1 = build.format = format; +var plugins_1 = build.plugins = void 0; + +var _ansiStyles = _interopRequireDefault(ansiStyles.exports); + +var _collections = collections; + +var _AsymmetricMatcher = _interopRequireDefault( + AsymmetricMatcher$1 +); + +var _ConvertAnsi = _interopRequireDefault(ConvertAnsi); + +var _DOMCollection = _interopRequireDefault(DOMCollection$1); + +var _DOMElement = _interopRequireDefault(DOMElement$1); + +var _Immutable = _interopRequireDefault(Immutable$1); + +var _ReactElement = _interopRequireDefault(ReactElement$1); + +var _ReactTestComponent = _interopRequireDefault( + ReactTestComponent$1 +); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually */ +const toString = Object.prototype.toString; +const toISOString = Date.prototype.toISOString; +const errorToString = Error.prototype.toString; +const regExpToString = RegExp.prototype.toString; +/** + * Explicitly comparing typeof constructor to function avoids undefined as name + * when mock identity-obj-proxy returns the key as the value for any key. + */ + +const getConstructorName = val => + (typeof val.constructor === 'function' && val.constructor.name) || 'Object'; +/* global window */ + +/** Is val is equal to global window object? Works even if it does not exist :) */ + +const isWindow = val => typeof window !== 'undefined' && val === window; + +const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; +const NEWLINE_REGEXP = /\n/gi; + +class PrettyFormatPluginError extends Error { + constructor(message, stack) { + super(message); + this.stack = stack; + this.name = this.constructor.name; + } +} + +function isToStringedArrayType(toStringed) { + return ( + toStringed === '[object Array]' || + toStringed === '[object ArrayBuffer]' || + toStringed === '[object DataView]' || + toStringed === '[object Float32Array]' || + toStringed === '[object Float64Array]' || + toStringed === '[object Int8Array]' || + toStringed === '[object Int16Array]' || + toStringed === '[object Int32Array]' || + toStringed === '[object Uint8Array]' || + toStringed === '[object Uint8ClampedArray]' || + toStringed === '[object Uint16Array]' || + toStringed === '[object Uint32Array]' + ); +} + +function printNumber(val) { + return Object.is(val, -0) ? '-0' : String(val); +} + +function printBigInt(val) { + return String(`${val}n`); +} + +function printFunction(val, printFunctionName) { + if (!printFunctionName) { + return '[Function]'; + } + + return '[Function ' + (val.name || 'anonymous') + ']'; +} + +function printSymbol(val) { + return String(val).replace(SYMBOL_REGEXP, 'Symbol($1)'); +} + +function printError(val) { + return '[' + errorToString.call(val) + ']'; +} +/** + * The first port of call for printing an object, handles most of the + * data-types in JS. + */ + +function printBasicValue(val, printFunctionName, escapeRegex, escapeString) { + if (val === true || val === false) { + return '' + val; + } + + if (val === undefined) { + return 'undefined'; + } + + if (val === null) { + return 'null'; + } + + const typeOf = typeof val; + + if (typeOf === 'number') { + return printNumber(val); + } + + if (typeOf === 'bigint') { + return printBigInt(val); + } + + if (typeOf === 'string') { + if (escapeString) { + return '"' + val.replace(/"|\\/g, '\\$&') + '"'; + } + + return '"' + val + '"'; + } + + if (typeOf === 'function') { + return printFunction(val, printFunctionName); + } + + if (typeOf === 'symbol') { + return printSymbol(val); + } + + const toStringed = toString.call(val); + + if (toStringed === '[object WeakMap]') { + return 'WeakMap {}'; + } + + if (toStringed === '[object WeakSet]') { + return 'WeakSet {}'; + } + + if ( + toStringed === '[object Function]' || + toStringed === '[object GeneratorFunction]' + ) { + return printFunction(val, printFunctionName); + } + + if (toStringed === '[object Symbol]') { + return printSymbol(val); + } + + if (toStringed === '[object Date]') { + return isNaN(+val) ? 'Date { NaN }' : toISOString.call(val); + } + + if (toStringed === '[object Error]') { + return printError(val); + } + + if (toStringed === '[object RegExp]') { + if (escapeRegex) { + // https://github.com/benjamingr/RegExp.escape/blob/main/polyfill.js + return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); + } + + return regExpToString.call(val); + } + + if (val instanceof Error) { + return printError(val); + } + + return null; +} +/** + * Handles more complex objects ( such as objects with circular references. + * maps and sets etc ) + */ + +function printComplexValue( + val, + config, + indentation, + depth, + refs, + hasCalledToJSON +) { + if (refs.indexOf(val) !== -1) { + return '[Circular]'; + } + + refs = refs.slice(); + refs.push(val); + const hitMaxDepth = ++depth > config.maxDepth; + const min = config.min; + + if ( + config.callToJSON && + !hitMaxDepth && + val.toJSON && + typeof val.toJSON === 'function' && + !hasCalledToJSON + ) { + return printer(val.toJSON(), config, indentation, depth, refs, true); + } + + const toStringed = toString.call(val); + + if (toStringed === '[object Arguments]') { + return hitMaxDepth + ? '[Arguments]' + : (min ? '' : 'Arguments ') + + '[' + + (0, _collections.printListItems)( + val, + config, + indentation, + depth, + refs, + printer + ) + + ']'; + } + + if (isToStringedArrayType(toStringed)) { + return hitMaxDepth + ? '[' + val.constructor.name + ']' + : (min + ? '' + : !config.printBasicPrototype && val.constructor.name === 'Array' + ? '' + : val.constructor.name + ' ') + + '[' + + (0, _collections.printListItems)( + val, + config, + indentation, + depth, + refs, + printer + ) + + ']'; + } + + if (toStringed === '[object Map]') { + return hitMaxDepth + ? '[Map]' + : 'Map {' + + (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer, + ' => ' + ) + + '}'; + } + + if (toStringed === '[object Set]') { + return hitMaxDepth + ? '[Set]' + : 'Set {' + + (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + + '}'; + } // Avoid failure to serialize global window object in jsdom test environment. + // For example, not even relevant if window is prop of React element. + + return hitMaxDepth || isWindow(val) + ? '[' + getConstructorName(val) + ']' + : (min + ? '' + : !config.printBasicPrototype && getConstructorName(val) === 'Object' + ? '' + : getConstructorName(val) + ' ') + + '{' + + (0, _collections.printObjectProperties)( + val, + config, + indentation, + depth, + refs, + printer + ) + + '}'; +} + +function isNewPlugin(plugin) { + return plugin.serialize != null; +} + +function printPlugin(plugin, val, config, indentation, depth, refs) { + let printed; + + try { + printed = isNewPlugin(plugin) + ? plugin.serialize(val, config, indentation, depth, refs, printer) + : plugin.print( + val, + valChild => printer(valChild, config, indentation, depth, refs), + str => { + const indentationNext = indentation + config.indent; + return ( + indentationNext + + str.replace(NEWLINE_REGEXP, '\n' + indentationNext) + ); + }, + { + edgeSpacing: config.spacingOuter, + min: config.min, + spacing: config.spacingInner + }, + config.colors + ); + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + + if (typeof printed !== 'string') { + throw new Error( + `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".` + ); + } + + return printed; +} + +function findPlugin(plugins, val) { + for (let p = 0; p < plugins.length; p++) { + try { + if (plugins[p].test(val)) { + return plugins[p]; + } + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + } + + return null; +} + +function printer(val, config, indentation, depth, refs, hasCalledToJSON) { + const plugin = findPlugin(config.plugins, val); + + if (plugin !== null) { + return printPlugin(plugin, val, config, indentation, depth, refs); + } + + const basicResult = printBasicValue( + val, + config.printFunctionName, + config.escapeRegex, + config.escapeString + ); + + if (basicResult !== null) { + return basicResult; + } + + return printComplexValue( + val, + config, + indentation, + depth, + refs, + hasCalledToJSON + ); +} + +const DEFAULT_THEME = { + comment: 'gray', + content: 'reset', + prop: 'yellow', + tag: 'cyan', + value: 'green' +}; +const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); +const DEFAULT_OPTIONS = { + callToJSON: true, + compareKeys: undefined, + escapeRegex: false, + escapeString: true, + highlight: false, + indent: 2, + maxDepth: Infinity, + min: false, + plugins: [], + printBasicPrototype: true, + printFunctionName: true, + theme: DEFAULT_THEME +}; +build.DEFAULT_OPTIONS = DEFAULT_OPTIONS; + +function validateOptions(options) { + Object.keys(options).forEach(key => { + if (!DEFAULT_OPTIONS.hasOwnProperty(key)) { + throw new Error(`pretty-format: Unknown option "${key}".`); + } + }); + + if (options.min && options.indent !== undefined && options.indent !== 0) { + throw new Error( + 'pretty-format: Options "min" and "indent" cannot be used together.' + ); + } + + if (options.theme !== undefined) { + if (options.theme === null) { + throw new Error('pretty-format: Option "theme" must not be null.'); + } + + if (typeof options.theme !== 'object') { + throw new Error( + `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".` + ); + } + } +} + +const getColorsHighlight = options => + DEFAULT_THEME_KEYS.reduce((colors, key) => { + const value = + options.theme && options.theme[key] !== undefined + ? options.theme[key] + : DEFAULT_THEME[key]; + const color = value && _ansiStyles.default[value]; + + if ( + color && + typeof color.close === 'string' && + typeof color.open === 'string' + ) { + colors[key] = color; + } else { + throw new Error( + `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.` + ); + } + + return colors; + }, Object.create(null)); + +const getColorsEmpty = () => + DEFAULT_THEME_KEYS.reduce((colors, key) => { + colors[key] = { + close: '', + open: '' + }; + return colors; + }, Object.create(null)); + +const getPrintFunctionName = options => + options && options.printFunctionName !== undefined + ? options.printFunctionName + : DEFAULT_OPTIONS.printFunctionName; + +const getEscapeRegex = options => + options && options.escapeRegex !== undefined + ? options.escapeRegex + : DEFAULT_OPTIONS.escapeRegex; + +const getEscapeString = options => + options && options.escapeString !== undefined + ? options.escapeString + : DEFAULT_OPTIONS.escapeString; + +const getConfig = options => { + var _options$printBasicPr; + + return { + callToJSON: + options && options.callToJSON !== undefined + ? options.callToJSON + : DEFAULT_OPTIONS.callToJSON, + colors: + options && options.highlight + ? getColorsHighlight(options) + : getColorsEmpty(), + compareKeys: + options && typeof options.compareKeys === 'function' + ? options.compareKeys + : DEFAULT_OPTIONS.compareKeys, + escapeRegex: getEscapeRegex(options), + escapeString: getEscapeString(options), + indent: + options && options.min + ? '' + : createIndent( + options && options.indent !== undefined + ? options.indent + : DEFAULT_OPTIONS.indent + ), + maxDepth: + options && options.maxDepth !== undefined + ? options.maxDepth + : DEFAULT_OPTIONS.maxDepth, + min: + options && options.min !== undefined ? options.min : DEFAULT_OPTIONS.min, + plugins: + options && options.plugins !== undefined + ? options.plugins + : DEFAULT_OPTIONS.plugins, + printBasicPrototype: + (_options$printBasicPr = + options === null || options === void 0 + ? void 0 + : options.printBasicPrototype) !== null && + _options$printBasicPr !== void 0 + ? _options$printBasicPr + : true, + printFunctionName: getPrintFunctionName(options), + spacingInner: options && options.min ? ' ' : '\n', + spacingOuter: options && options.min ? '' : '\n' + }; +}; + +function createIndent(indent) { + return new Array(indent + 1).join(' '); +} +/** + * Returns a presentation string of your `val` object + * @param val any potential JavaScript object + * @param options Custom settings + */ + +function format(val, options) { + if (options) { + validateOptions(options); + + if (options.plugins) { + const plugin = findPlugin(options.plugins, val); + + if (plugin !== null) { + return printPlugin(plugin, val, getConfig(options), '', 0, []); + } + } + } + + const basicResult = printBasicValue( + val, + getPrintFunctionName(options), + getEscapeRegex(options), + getEscapeString(options) + ); + + if (basicResult !== null) { + return basicResult; + } + + return printComplexValue(val, getConfig(options), '', 0, []); +} + +const plugins = { + AsymmetricMatcher: _AsymmetricMatcher.default, + ConvertAnsi: _ConvertAnsi.default, + DOMCollection: _DOMCollection.default, + DOMElement: _DOMElement.default, + Immutable: _Immutable.default, + ReactElement: _ReactElement.default, + ReactTestComponent: _ReactTestComponent.default +}; +plugins_1 = build.plugins = plugins; +var _default = format; +build.default = _default; + +const { + AsymmetricMatcher, + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent +} = plugins_1; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher +]; +function stringify(object, maxDepth = 10, { maxLength, ...options } = {}) { + const MAX_LENGTH = maxLength ?? 1e4; + let result; + try { + result = format_1(object, { + maxDepth, + escapeString: false, + plugins: PLUGINS, + ...options + }); + } catch { + result = format_1(object, { + callToJSON: false, + maxDepth, + escapeString: false, + plugins: PLUGINS, + ...options + }); + } + return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object, Math.floor(maxDepth / 2)) : result; +} + +export { stringify as a, safeClearTimeout as b, createPatch as c, ansiStyles$1 as d, eastAsianWidth as e, format_1 as f, safeSetInterval as g, safeClearInterval as h, plugins_1 as p, safeSetTimeout as s }; diff --git a/node_modules/vitest/dist/cli-wrapper.js b/node_modules/vitest/dist/cli-wrapper.js new file mode 100644 index 0000000..7062afb --- /dev/null +++ b/node_modules/vitest/dist/cli-wrapper.js @@ -0,0 +1,138 @@ +import { fileURLToPath } from 'url'; +import c from 'picocolors'; +import { e as execa } from './vendor-index.b2fdde54.js'; +import { E as EXIT_CODE_RESTART } from './chunk-utils-env.b861e3a0.js'; +import 'node:buffer'; +import 'node:path'; +import 'node:child_process'; +import 'node:process'; +import './vendor-index.7a2cebfe.js'; +import 'child_process'; +import 'path'; +import './vendor-_commonjsHelpers.addc3445.js'; +import 'fs'; +import 'assert'; +import 'events'; +import 'buffer'; +import 'stream'; +import 'util'; +import 'node:url'; +import 'os'; +import 'node:os'; + +const ENTRY = new URL("./cli.js", import.meta.url); +const NODE_ARGS = [ + "--inspect", + "--inspect-brk", + "--trace-deprecation", + "--experimental-wasm-threads", + "--wasm-atomics-on-non-shared-memory" +]; +const SegfaultErrors = [ + { + trigger: "Check failed: result.second.", + url: "https://github.com/nodejs/node/issues/43617" + }, + { + trigger: "FATAL ERROR: v8::FromJust Maybe value is Nothing.", + url: "https://github.com/vitest-dev/vitest/issues/1191" + }, + { + trigger: "FATAL ERROR: v8::ToLocalChecked Empty MaybeLocal.", + url: "https://github.com/nodejs/node/issues/42407" + } +]; +main(); +async function main() { + var _a; + let retries = 0; + const args = process.argv.slice(2); + if (process.env.VITEST_SEGFAULT_RETRY) { + retries = +process.env.VITEST_SEGFAULT_RETRY; + } else { + for (let i = 0; i < args.length; i++) { + if (args[i].startsWith("--segfault-retry=")) { + retries = +args[i].split("=")[1]; + break; + } else if (args[i] === "--segfault-retry" && ((_a = args[i + 1]) == null ? void 0 : _a.match(/^\d+$/))) { + retries = +args[i + 1]; + break; + } + } + } + if (retries <= 0) { + await import('./cli.js'); + return; + } + const nodeArgs = []; + const vitestArgs = []; + for (let i = 0; i < args.length; i++) { + let matched = false; + for (const nodeArg of NODE_ARGS) { + if (args[i] === nodeArg || args[i].startsWith(`${nodeArg}=`)) { + matched = true; + nodeArgs.push(args[i]); + break; + } + } + if (!matched) + vitestArgs.push(args[i]); + } + retries = Math.max(1, retries || 1); + for (let i = 1; i <= retries; i++) { + const result = await start(nodeArgs, vitestArgs); + if (result === "restart") { + i -= 1; + continue; + } + if (i === 1 && retries === 1) { + console.log(c.yellow(`It seems to be an upstream bug of Node.js. To improve the test stability, +you could pass ${c.bold(c.green("--segfault-retry=3"))} or set env ${c.bold(c.green("VITEST_SEGFAULT_RETRY=3"))} to +have Vitest auto retries on flaky segfaults. +`)); + } + if (i !== retries) + console.log(`${c.inverse(c.bold(c.magenta(" Retrying ")))} vitest ${args.join(" ")} ${c.gray(`(${i + 1} of ${retries})`)}`); + } + process.exit(1); +} +async function start(preArgs, postArgs) { + var _a; + const child = execa( + "node", + [ + ...preArgs, + fileURLToPath(ENTRY), + ...postArgs + ], + { + reject: false, + stderr: "pipe", + stdout: "inherit", + stdin: "inherit", + env: { + ...process.env, + VITEST_CLI_WRAPPER: "true" + } + } + ); + (_a = child.stderr) == null ? void 0 : _a.pipe(process.stderr); + const { stderr = "" } = await child; + if (child.exitCode === EXIT_CODE_RESTART) + return "restart"; + for (const error of SegfaultErrors) { + if (stderr.includes(error.trigger)) { + if (process.env.GITHUB_ACTIONS) + console.log(`::warning:: Segmentfault Error Detected: ${error.trigger} +Refer to ${error.url}`); + const RED_BLOCK = c.inverse(c.red(" ")); + console.log(` +${c.inverse(c.bold(c.red(" Segmentfault Error Detected ")))} +${RED_BLOCK} ${c.red(error.trigger)} +${RED_BLOCK} ${c.red(`Refer to ${error.url}`)} +`); + return "error"; + } + } + process.exit(child.exitCode); +} diff --git a/node_modules/vitest/dist/cli.js b/node_modules/vitest/dist/cli.js new file mode 100644 index 0000000..1d9fd05 --- /dev/null +++ b/node_modules/vitest/dist/cli.js @@ -0,0 +1,111 @@ +import { n as normalize } from './chunk-utils-env.b861e3a0.js'; +import cac from 'cac'; +import c from 'picocolors'; +import { v as version, s as startVitest, d as divider } from './chunk-snapshot-manager.700322bf.js'; +import 'node:url'; +import 'path'; +import './chunk-integrations-coverage.44413252.js'; +import 'local-pkg'; +import './chunk-env-node.b3664da2.js'; +import 'node:console'; +import './chunk-mock-date.a1c85759.js'; +import 'node:path'; +import 'vite'; +import 'node:process'; +import 'node:fs'; +import 'os'; +import 'util'; +import 'stream'; +import 'events'; +import 'fs'; +import './vendor-_commonjsHelpers.addc3445.js'; +import 'vite-node/client'; +import 'vite-node/server'; +import 'node:fs/promises'; +import './vendor-index.b2fdde54.js'; +import 'node:buffer'; +import 'node:child_process'; +import './vendor-index.7a2cebfe.js'; +import 'child_process'; +import 'assert'; +import 'buffer'; +import 'node:os'; +import 'source-map'; +import 'module'; +import 'acorn'; +import 'acorn-walk'; +import 'node:worker_threads'; +import 'tinypool'; +import './vendor-index.783e7f3e.js'; +import 'perf_hooks'; +import './chunk-utils-source-map.60562959.js'; +import './chunk-utils-timers.52534f96.js'; +import 'crypto'; +import 'vite-node/utils'; +import './vendor-index.9c919048.js'; +import 'node:crypto'; +import './chunk-magic-string.3a794426.js'; +import 'strip-literal'; +import 'readline'; +import './vendor-index.9f20a9be.js'; + +const cli = cac("vitest"); +cli.version(version).option("-r, --root ", "root path").option("-c, --config ", "path to config file").option("-u, --update", "update snapshot").option("-w, --watch", "watch mode").option("-t, --testNamePattern ", "run tests with full names matching the specified pattern").option("--dir ", "base directory to scan for the test files").option("--ui", "enable UI").option("--open", "open UI automatically (default: !process.env.CI))").option("--api [api]", "serve API, available options: --api.port , --api.host [host] and --api.strictPort").option("--threads", "enabled threads (default: true)").option("--silent", "silent console output from tests").option("--isolate", "isolate environment for each test file (default: true)").option("--reporter ", "reporter").option("--outputDiffMaxSize ", "object diff output max size (default: 10000)").option("--outputDiffMaxLines ", "max lines in diff output window (default: 50)").option("--outputTruncateLength ", "diff output line length (default: 80)").option("--outputDiffLines ", "number of lines in single diff (default: 15)").option("--outputFile ", "write test results to a file when the --reporter=json or --reporter=junit option is also specified, use cac's dot notation for individual outputs of multiple reporters").option("--coverage", "enable coverage report").option("--run", "do not watch").option("--mode ", "override Vite mode (default: test)").option("--globals", "inject apis globally").option("--dom", "mock browser api with happy-dom").option("--browser", "run tests in browser").option("--environment ", "runner environment (default: node)").option("--passWithNoTests", "pass when no tests found").option("--logHeapUsage", "show the size of heap for each test").option("--allowOnly", "Allow tests and suites that are marked as only (default: !process.env.CI)").option("--dangerouslyIgnoreUnhandledErrors", "Ignore any unhandled errors that occur").option("--shard ", "Test suite shard to execute in a format of /").option("--changed [since]", "Run tests that are affected by the changed files (default: false)").option("--sequence ", "Define in what order to run tests (use --sequence.shuffle to run tests in random order)").option("--no-color", "Removes colors from the console output").option("--segfault-retry ", "Return tests on segment fault (default: 0)", { default: 0 }).option("--inspect", "Enable Node.js inspector").option("--inspect-brk", "Enable Node.js inspector with break").help(); +cli.command("run [...filters]").action(run); +cli.command("related [...filters]").action(runRelated); +cli.command("watch [...filters]").action(watch); +cli.command("dev [...filters]").action(watch); +cli.command("bench [...filters]").action(benchmark); +cli.command("typecheck [...filters]").action(typecheck); +cli.command("[...filters]").action((filters, options) => start("test", filters, options)); +cli.parse(); +async function runRelated(relatedFiles, argv) { + argv.related = relatedFiles; + argv.passWithNoTests ?? (argv.passWithNoTests = true); + await start("test", [], argv); +} +async function watch(cliFilters, options) { + options.watch = true; + await start("test", cliFilters, options); +} +async function run(cliFilters, options) { + options.run = true; + await start("test", cliFilters, options); +} +async function benchmark(cliFilters, options) { + console.warn(c.yellow("Benchmarking is an experimental feature.\nBreaking changes might not follow semver, please pin Vitest's version when using it.")); + await start("benchmark", cliFilters, options); +} +async function typecheck(cliFilters = [], options = {}) { + console.warn(c.yellow("Testing types with tsc and vue-tsc is an experimental feature.\nBreaking changes might not follow semver, please pin Vitest's version when using it.")); + await start("typecheck", cliFilters, options); +} +function normalizeCliOptions(argv) { + if (argv.root) + argv.root = normalize(argv.root); + else + delete argv.root; + if (argv.config) + argv.config = normalize(argv.config); + else + delete argv.config; + if (argv.dir) + argv.dir = normalize(argv.dir); + else + delete argv.dir; + return argv; +} +async function start(mode, cliFilters, options) { + try { + const ctx = await startVitest(mode, cliFilters.map(normalize), normalizeCliOptions(options)); + if (!(ctx == null ? void 0 : ctx.config.watch)) + await (ctx == null ? void 0 : ctx.exit()); + return ctx; + } catch (e) { + console.error(` +${c.red(divider(c.bold(c.inverse(" Unhandled Error "))))}`); + console.error(e); + console.error("\n\n"); + process.exit(1); + } +} diff --git a/node_modules/vitest/dist/config.cjs b/node_modules/vitest/dist/config.cjs new file mode 100644 index 0000000..6a9efae --- /dev/null +++ b/node_modules/vitest/dist/config.cjs @@ -0,0 +1,97 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +const defaultInclude = ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"]; +const defaultExclude = ["**/node_modules/**", "**/dist/**", "**/cypress/**", "**/.{idea,git,cache,output,temp}/**", "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*"]; +const defaultCoverageExcludes = [ + "coverage/**", + "dist/**", + "packages/*/test{,s}/**", + "**/*.d.ts", + "cypress/**", + "test{,s}/**", + "test{,-*}.{js,cjs,mjs,ts,tsx,jsx}", + "**/*{.,-}test.{js,cjs,mjs,ts,tsx,jsx}", + "**/*{.,-}spec.{js,cjs,mjs,ts,tsx,jsx}", + "**/__tests__/**", + "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*", + "**/.{eslint,mocha,prettier}rc.{js,cjs,yml}" +]; +const coverageConfigDefaults = { + all: false, + provider: "c8", + enabled: false, + clean: true, + cleanOnRerun: true, + reportsDirectory: "./coverage", + excludeNodeModules: true, + exclude: defaultCoverageExcludes, + reporter: ["text", "html", "clover", "json"], + allowExternal: false, + extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"] +}; +const fakeTimersDefaults = { + loopLimit: 1e4, + shouldClearNativeTimers: true, + toFake: [ + "setTimeout", + "clearTimeout", + "setInterval", + "clearInterval", + "setImmediate", + "clearImmediate", + "Date" + ] +}; +const config = { + allowOnly: !process.env.CI, + watch: !process.env.CI, + globals: false, + environment: "node", + threads: true, + clearMocks: false, + restoreMocks: false, + mockReset: false, + include: defaultInclude, + exclude: defaultExclude, + testTimeout: 5e3, + hookTimeout: 1e4, + teardownTimeout: 1e3, + isolate: true, + watchExclude: ["**/node_modules/**", "**/dist/**"], + forceRerunTriggers: [ + "**/package.json/**", + "**/{vitest,vite}.config.*/**" + ], + update: false, + reporters: [], + silent: false, + api: false, + ui: false, + uiBase: "/__vitest__/", + open: true, + css: { + include: [] + }, + coverage: coverageConfigDefaults, + fakeTimers: fakeTimersDefaults, + maxConcurrency: 5, + dangerouslyIgnoreUnhandledErrors: false, + typecheck: { + checker: "tsc", + include: ["**/*.{test,spec}-d.{ts,js}"], + exclude: defaultExclude + }, + slowTestThreshold: 300 +}; +const configDefaults = Object.freeze(config); + +function defineConfig(config) { + return config; +} + +exports.configDefaults = configDefaults; +exports.defaultExclude = defaultExclude; +exports.defaultInclude = defaultInclude; +exports.defineConfig = defineConfig; diff --git a/node_modules/vitest/dist/config.d.ts b/node_modules/vitest/dist/config.d.ts new file mode 100644 index 0000000..c58782b --- /dev/null +++ b/node_modules/vitest/dist/config.d.ts @@ -0,0 +1,61 @@ +import { UserConfig as UserConfig$2, ConfigEnv } from 'vite'; +export { ConfigEnv } from 'vite'; +import { U as UserConfig$1, an as ResolvedCoverageOptions, F as FakeTimerInstallOpts } from './types-e1e1d1e5.js'; +import 'tinybench'; +import 'vite-node/client'; +import 'vite-node/server'; +import 'vite-node'; +import 'node:fs'; +import 'node:worker_threads'; + +declare const defaultInclude: string[]; +declare const defaultExclude: string[]; +declare const config: { + allowOnly: boolean; + watch: boolean; + globals: boolean; + environment: "node"; + threads: boolean; + clearMocks: boolean; + restoreMocks: boolean; + mockReset: boolean; + include: string[]; + exclude: string[]; + testTimeout: number; + hookTimeout: number; + teardownTimeout: number; + isolate: boolean; + watchExclude: string[]; + forceRerunTriggers: string[]; + update: boolean; + reporters: never[]; + silent: boolean; + api: boolean; + ui: boolean; + uiBase: string; + open: boolean; + css: { + include: never[]; + }; + coverage: ResolvedCoverageOptions; + fakeTimers: FakeTimerInstallOpts; + maxConcurrency: number; + dangerouslyIgnoreUnhandledErrors: boolean; + typecheck: { + checker: "tsc"; + include: string[]; + exclude: string[]; + }; + slowTestThreshold: number; +}; +declare const configDefaults: Required>; + +interface UserConfig extends UserConfig$2 { + test?: UserConfig$2['test']; +} + +type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise; +type UserConfigExport = UserConfig | Promise | UserConfigFn; +declare function defineConfig(config: UserConfigExport): UserConfigExport; + +export { UserConfig, UserConfigExport, UserConfigFn, configDefaults, defaultExclude, defaultInclude, defineConfig }; diff --git a/node_modules/vitest/dist/config.js b/node_modules/vitest/dist/config.js new file mode 100644 index 0000000..93f8ae5 --- /dev/null +++ b/node_modules/vitest/dist/config.js @@ -0,0 +1,90 @@ +const defaultInclude = ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"]; +const defaultExclude = ["**/node_modules/**", "**/dist/**", "**/cypress/**", "**/.{idea,git,cache,output,temp}/**", "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*"]; +const defaultCoverageExcludes = [ + "coverage/**", + "dist/**", + "packages/*/test{,s}/**", + "**/*.d.ts", + "cypress/**", + "test{,s}/**", + "test{,-*}.{js,cjs,mjs,ts,tsx,jsx}", + "**/*{.,-}test.{js,cjs,mjs,ts,tsx,jsx}", + "**/*{.,-}spec.{js,cjs,mjs,ts,tsx,jsx}", + "**/__tests__/**", + "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*", + "**/.{eslint,mocha,prettier}rc.{js,cjs,yml}" +]; +const coverageConfigDefaults = { + all: false, + provider: "c8", + enabled: false, + clean: true, + cleanOnRerun: true, + reportsDirectory: "./coverage", + excludeNodeModules: true, + exclude: defaultCoverageExcludes, + reporter: ["text", "html", "clover", "json"], + allowExternal: false, + extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"] +}; +const fakeTimersDefaults = { + loopLimit: 1e4, + shouldClearNativeTimers: true, + toFake: [ + "setTimeout", + "clearTimeout", + "setInterval", + "clearInterval", + "setImmediate", + "clearImmediate", + "Date" + ] +}; +const config = { + allowOnly: !process.env.CI, + watch: !process.env.CI, + globals: false, + environment: "node", + threads: true, + clearMocks: false, + restoreMocks: false, + mockReset: false, + include: defaultInclude, + exclude: defaultExclude, + testTimeout: 5e3, + hookTimeout: 1e4, + teardownTimeout: 1e3, + isolate: true, + watchExclude: ["**/node_modules/**", "**/dist/**"], + forceRerunTriggers: [ + "**/package.json/**", + "**/{vitest,vite}.config.*/**" + ], + update: false, + reporters: [], + silent: false, + api: false, + ui: false, + uiBase: "/__vitest__/", + open: true, + css: { + include: [] + }, + coverage: coverageConfigDefaults, + fakeTimers: fakeTimersDefaults, + maxConcurrency: 5, + dangerouslyIgnoreUnhandledErrors: false, + typecheck: { + checker: "tsc", + include: ["**/*.{test,spec}-d.{ts,js}"], + exclude: defaultExclude + }, + slowTestThreshold: 300 +}; +const configDefaults = Object.freeze(config); + +function defineConfig(config) { + return config; +} + +export { configDefaults, defaultExclude, defaultInclude, defineConfig }; diff --git a/node_modules/vitest/dist/entry.js b/node_modules/vitest/dist/entry.js new file mode 100644 index 0000000..7f375fd --- /dev/null +++ b/node_modules/vitest/dist/entry.js @@ -0,0 +1,86 @@ +import { promises } from 'node:fs'; +import { g as getWorkerState, a as resetModules } from './chunk-mock-date.a1c85759.js'; +import { v as vi } from './chunk-utils-import.2baa69a9.js'; +import { a as envs } from './chunk-env-node.b3664da2.js'; +import { a as setupGlobalEnv, s as startTests, w as withEnv } from './chunk-runtime-setup.731b2b04.js'; +import 'node:path'; +import 'picocolors'; +import 'local-pkg'; +import './chunk-utils-env.b861e3a0.js'; +import 'node:url'; +import 'path'; +import './chunk-runtime-chain.6df5a66b.js'; +import 'util'; +import 'chai'; +import './vendor-_commonjsHelpers.addc3445.js'; +import './chunk-utils-timers.52534f96.js'; +import './vendor-index.723a074f.js'; +import 'tinyspy'; +import './chunk-utils-source-map.60562959.js'; +import './chunk-runtime-rpc.7f83c8a9.js'; +import 'fs'; +import 'node:console'; +import 'perf_hooks'; +import './chunk-integrations-coverage.44413252.js'; +import './chunk-runtime-error.fad2c32b.js'; +import 'vite-node/source-map'; + +function groupBy(collection, iteratee) { + return collection.reduce((acc, item) => { + const key = iteratee(item); + acc[key] || (acc[key] = []); + acc[key].push(item); + return acc; + }, {}); +} +async function run(files, config) { + await setupGlobalEnv(config); + const workerState = getWorkerState(); + if (config.browser) { + workerState.mockMap.clear(); + await startTests(files, config); + return; + } + const filesWithEnv = await Promise.all(files.map(async (file) => { + var _a, _b; + const code = await promises.readFile(file, "utf-8"); + const env = ((_a = code.match(/@(?:vitest|jest)-environment\s+?([\w-]+)\b/)) == null ? void 0 : _a[1]) || config.environment || "node"; + const envOptions = JSON.parse(((_b = code.match(/@(?:vitest|jest)-environment-options\s+?(.+)/)) == null ? void 0 : _b[1]) || "null"); + return { + file, + env, + envOptions: envOptions ? { [env]: envOptions } : null + }; + })); + const filesByEnv = groupBy(filesWithEnv, ({ env }) => env); + const orderedEnvs = envs.concat( + Object.keys(filesByEnv).filter((env) => !envs.includes(env)) + ); + for (const env of orderedEnvs) { + const environment = env; + const files2 = filesByEnv[environment]; + if (!files2 || !files2.length) + continue; + globalThis.__vitest_environment__ = environment; + const filesByOptions = groupBy(files2, ({ envOptions }) => JSON.stringify(envOptions)); + for (const options of Object.keys(filesByOptions)) { + const files3 = filesByOptions[options]; + if (!files3 || !files3.length) + continue; + await withEnv(environment, files3[0].envOptions || config.environmentOptions || {}, async () => { + for (const { file } of files3) { + if (config.isolate) { + workerState.mockMap.clear(); + resetModules(workerState.moduleCache, true); + } + workerState.filepath = file; + await startTests([file], config); + workerState.filepath = void 0; + vi.resetConfig(); + } + }); + } + } +} + +export { run }; diff --git a/node_modules/vitest/dist/environments.d.ts b/node_modules/vitest/dist/environments.d.ts new file mode 100644 index 0000000..b1ef1bf --- /dev/null +++ b/node_modules/vitest/dist/environments.d.ts @@ -0,0 +1,26 @@ +import { ae as Environment } from './types-e1e1d1e5.js'; +import 'vite'; +import 'tinybench'; +import 'vite-node/client'; +import 'vite-node/server'; +import 'vite-node'; +import 'node:fs'; +import 'node:worker_threads'; + +declare const environments: { + node: Environment; + jsdom: Environment; + 'happy-dom': Environment; + 'edge-runtime': Environment; +}; + +interface PopulateOptions { + bindFunctions?: boolean; +} +declare function populateGlobal(global: any, win: any, options?: PopulateOptions): { + keys: Set; + skipKeys: string[]; + originals: Map; +}; + +export { environments as builtinEnvironments, populateGlobal }; diff --git a/node_modules/vitest/dist/environments.js b/node_modules/vitest/dist/environments.js new file mode 100644 index 0000000..c4df5b6 --- /dev/null +++ b/node_modules/vitest/dist/environments.js @@ -0,0 +1,3 @@ +export { e as builtinEnvironments, p as populateGlobal } from './chunk-env-node.b3664da2.js'; +import 'node:console'; +import 'local-pkg'; diff --git a/node_modules/vitest/dist/index-2d10c3fd.d.ts b/node_modules/vitest/dist/index-2d10c3fd.d.ts new file mode 100644 index 0000000..0b1d362 --- /dev/null +++ b/node_modules/vitest/dist/index-2d10c3fd.d.ts @@ -0,0 +1,256 @@ +import { SpyImpl } from 'tinyspy'; +import { w as SuiteAPI, v as TestAPI, av as BenchmarkAPI, y as SuiteHooks, H as HookListener, L as TestContext, q as Suite, x as HookCleanupCallback, O as OnTestFailedHandler, r as Test } from './types-e1e1d1e5.js'; + +declare type Not = T extends true ? false : true; +declare type And = Types[number] extends true ? true : false; +declare type Eq = Left extends true ? Right : Not; +declare const secret: unique symbol; +declare type Secret = typeof secret; +declare type IsNever = [T] extends [never] ? true : false; +declare type IsAny = [T] extends [Secret] ? Not> : false; +declare type IsUnknown = [unknown] extends [T] ? Not> : false; +/** + * Recursively walk a type and replace it with a branded type related to the original. This is useful for + * equality-checking stricter than `A extends B ? B extends A ? true : false : false`, because it detects + * the difference between a few edge-case types that vanilla typescript doesn't by default: + * - `any` vs `unknown` + * - `{ readonly a: string }` vs `{ a: string }` + * - `{ a?: string }` vs `{ a: string | undefined }` + */ +declare type DeepBrand = IsNever extends true ? { + type: 'never'; +} : IsAny extends true ? { + type: 'any'; +} : IsUnknown extends true ? { + type: 'unknown'; +} : T extends string | number | boolean | symbol | bigint | null | undefined | void ? { + type: 'primitive'; + value: T; +} : T extends new (...args: any[]) => any ? { + type: 'constructor'; + params: ConstructorParams; + instance: DeepBrand any>>>; +} : T extends (...args: infer P) => infer R ? { + type: 'function'; + params: DeepBrand

; + return: DeepBrand; +} : T extends any[] ? { + type: 'array'; + items: { + [K in keyof T]: T[K]; + }; +} : { + type: 'object'; + properties: { + [K in keyof T]: DeepBrand; + }; + readonly: ReadonlyKeys; + required: RequiredKeys; + optional: OptionalKeys; + constructorParams: DeepBrand>; +}; +declare type RequiredKeys = Extract<{ + [K in keyof T]-?: {} extends Pick ? never : K; +}[keyof T], keyof T>; +declare type OptionalKeys = Exclude>; +declare type ReadonlyKeys = Extract<{ + [K in keyof T]-?: ReadonlyEquivalent<{ + [_K in K]: T[K]; + }, { + -readonly [_K in K]: T[K]; + }> extends true ? never : K; +}[keyof T], keyof T>; +declare type ReadonlyEquivalent = Extends<(() => T extends X ? true : false), (() => T extends Y ? true : false)>; +declare type Extends = IsNever extends true ? IsNever : [L] extends [R] ? true : false; +declare type StrictExtends = Extends, DeepBrand>; +declare type Equal = And<[StrictExtends, StrictExtends]>; +declare type Params = Actual extends (...args: infer P) => any ? P : never; +declare type ConstructorParams = Actual extends new (...args: infer P) => any ? Actual extends new () => any ? P | [] : P : never; +declare type MismatchArgs = Eq extends true ? [] : [never]; +interface ExpectTypeOf { + toBeAny: (...MISMATCH: MismatchArgs, B>) => true; + toBeUnknown: (...MISMATCH: MismatchArgs, B>) => true; + toBeNever: (...MISMATCH: MismatchArgs, B>) => true; + toBeFunction: (...MISMATCH: MismatchArgs any>, B>) => true; + toBeObject: (...MISMATCH: MismatchArgs, B>) => true; + toBeArray: (...MISMATCH: MismatchArgs, B>) => true; + toBeNumber: (...MISMATCH: MismatchArgs, B>) => true; + toBeString: (...MISMATCH: MismatchArgs, B>) => true; + toBeBoolean: (...MISMATCH: MismatchArgs, B>) => true; + toBeVoid: (...MISMATCH: MismatchArgs, B>) => true; + toBeSymbol: (...MISMATCH: MismatchArgs, B>) => true; + toBeNull: (...MISMATCH: MismatchArgs, B>) => true; + toBeUndefined: (...MISMATCH: MismatchArgs, B>) => true; + toBeNullable: (...MISMATCH: MismatchArgs>>, B>) => true; + toMatchTypeOf: { + (...MISMATCH: MismatchArgs, B>): true; + (expected: Expected, ...MISMATCH: MismatchArgs, B>): true; + }; + toEqualTypeOf: { + (...MISMATCH: MismatchArgs, B>): true; + (expected: Expected, ...MISMATCH: MismatchArgs, B>): true; + }; + toBeCallableWith: B extends true ? (...args: Params) => true : never; + toBeConstructibleWith: B extends true ? (...args: ConstructorParams) => true : never; + toHaveProperty: (key: K, ...MISMATCH: MismatchArgs, B>) => K extends keyof Actual ? ExpectTypeOf : true; + extract: (v?: V) => ExpectTypeOf, B>; + exclude: (v?: V) => ExpectTypeOf, B>; + parameter: >(number: K) => ExpectTypeOf[K], B>; + parameters: ExpectTypeOf, B>; + constructorParameters: ExpectTypeOf, B>; + instance: Actual extends new (...args: any[]) => infer I ? ExpectTypeOf : never; + returns: Actual extends (...args: any[]) => infer R ? ExpectTypeOf : never; + resolves: Actual extends PromiseLike ? ExpectTypeOf : never; + items: Actual extends ArrayLike ? ExpectTypeOf : never; + guards: Actual extends (v: any, ...args: any[]) => v is infer T ? ExpectTypeOf : never; + asserts: Actual extends (v: any, ...args: any[]) => asserts v is infer T ? unknown extends T ? never : ExpectTypeOf : never; + not: ExpectTypeOf>; +} +declare type _ExpectTypeOf = { + (actual: Actual): ExpectTypeOf; + (): ExpectTypeOf; +}; +/** + * Similar to Jest's `expect`, but with type-awareness. + * Gives you access to a number of type-matchers that let you make assertions about the + * form of a reference or generic type parameter. + * + * @example + * import {foo, bar} from '../foo' + * import {expectTypeOf} from 'expect-type' + * + * test('foo types', () => { + * // make sure `foo` has type {a: number} + * expectTypeOf(foo).toMatchTypeOf({a: 1}) + * expectTypeOf(foo).toHaveProperty('a').toBeNumber() + * + * // make sure `bar` is a function taking a string: + * expectTypeOf(bar).parameter(0).toBeString() + * expectTypeOf(bar).returns.not.toBeAny() + * }) + * + * @description + * See the [full docs](https://npmjs.com/package/expect-type#documentation) for lots more examples. + */ +declare const expectTypeOf: _ExpectTypeOf; + +interface AssertType { + (value: T): void; +} +declare const assertType: AssertType; + +interface MockResultReturn { + type: 'return'; + value: T; +} +interface MockResultIncomplete { + type: 'incomplete'; + value: undefined; +} +interface MockResultThrow { + type: 'throw'; + value: any; +} +type MockResult = MockResultReturn | MockResultThrow | MockResultIncomplete; +interface MockContext { + calls: TArgs[]; + instances: TReturns[]; + invocationCallOrder: number[]; + results: MockResult[]; + lastCall: TArgs | undefined; +} +type Procedure = (...args: any[]) => any; +type Methods = { + [K in keyof T]: T[K] extends Procedure ? K : never; +}[keyof T] & (string | symbol); +type Properties = { + [K in keyof T]: T[K] extends Procedure ? never : K; +}[keyof T] & (string | symbol); +type Classes = { + [K in keyof T]: T[K] extends new (...args: any[]) => any ? K : never; +}[keyof T] & (string | symbol); +interface SpyInstance { + getMockName(): string; + mockName(n: string): this; + mock: MockContext; + mockClear(): this; + mockReset(): this; + mockRestore(): void; + getMockImplementation(): ((...args: TArgs) => TReturns) | undefined; + mockImplementation(fn: ((...args: TArgs) => TReturns) | (() => Promise)): this; + mockImplementationOnce(fn: ((...args: TArgs) => TReturns) | (() => Promise)): this; + mockReturnThis(): this; + mockReturnValue(obj: TReturns): this; + mockReturnValueOnce(obj: TReturns): this; + mockResolvedValue(obj: Awaited): this; + mockResolvedValueOnce(obj: Awaited): this; + mockRejectedValue(obj: any): this; + mockRejectedValueOnce(obj: any): this; +} +interface MockInstance extends SpyInstance { +} +interface Mock extends SpyInstance { + new (...args: TArgs): TReturns; + (...args: TArgs): TReturns; +} +interface PartialMock extends SpyInstance> { + new (...args: TArgs): TReturns; + (...args: TArgs): TReturns; +} +type MaybeMockedConstructor = T extends new (...args: Array) => infer R ? Mock, R> : T; +type MockedFunction = Mock, ReturnType> & { + [K in keyof T]: T[K]; +}; +type PartiallyMockedFunction = PartialMock, ReturnType> & { + [K in keyof T]: T[K]; +}; +type MockedFunctionDeep = Mock, ReturnType> & MockedObjectDeep; +type PartiallyMockedFunctionDeep = PartialMock, ReturnType> & MockedObjectDeep; +type MockedObject = MaybeMockedConstructor & { + [K in Methods]: T[K] extends Procedure ? MockedFunction : T[K]; +} & { + [K in Properties]: T[K]; +}; +type MockedObjectDeep = MaybeMockedConstructor & { + [K in Methods]: T[K] extends Procedure ? MockedFunctionDeep : T[K]; +} & { + [K in Properties]: MaybeMockedDeep; +}; +type MaybeMockedDeep = T extends Procedure ? MockedFunctionDeep : T extends object ? MockedObjectDeep : T; +type MaybePartiallyMockedDeep = T extends Procedure ? PartiallyMockedFunctionDeep : T extends object ? MockedObjectDeep : T; +type MaybeMocked = T extends Procedure ? MockedFunction : T extends object ? MockedObject : T; +type MaybePartiallyMocked = T extends Procedure ? PartiallyMockedFunction : T extends object ? MockedObject : T; +interface Constructable { + new (...args: any[]): any; +} +type MockedClass = MockInstance any ? P : never, InstanceType> & { + prototype: T extends { + prototype: any; + } ? Mocked : never; +} & T; +type Mocked = { + [P in keyof T]: T[P] extends (...args: infer Args) => infer Returns ? MockInstance : T[P] extends Constructable ? MockedClass : T[P]; +} & T; +type EnhancedSpy = SpyInstance & SpyImpl; +declare function spyOn>>(obj: T, methodName: S, accessType: 'get'): SpyInstance<[], T[S]>; +declare function spyOn>>(obj: T, methodName: G, accessType: 'set'): SpyInstance<[T[G]], void>; +declare function spyOn> | Classes>)>(obj: T, methodName: M): Required[M] extends (...args: infer A) => infer R | (new (...args: infer A) => infer R) ? SpyInstance : never; +declare function fn(): Mock; +declare function fn(implementation: (...args: TArgs) => R): Mock; + +declare const suite: SuiteAPI<{}>; +declare const test: TestAPI<{}>; +declare const bench: BenchmarkAPI; +declare const describe: SuiteAPI<{}>; +declare const it: TestAPI<{}>; + +declare const beforeAll: (fn: SuiteHooks['beforeAll'][0], timeout?: number) => void; +declare const afterAll: (fn: SuiteHooks['afterAll'][0], timeout?: number) => void; +declare const beforeEach: (fn: HookListener<[TestContext & ExtraContext, Suite], HookCleanupCallback>, timeout?: number) => void; +declare const afterEach: (fn: HookListener<[TestContext & ExtraContext, Suite], void>, timeout?: number) => void; +declare const onTestFailed: (fn: OnTestFailedHandler) => void; + +declare function createExpect(test?: Test): Vi.ExpectStatic; +declare const globalExpect: Vi.ExpectStatic; + +export { AssertType as A, MockedClass as B, EnhancedSpy as E, MaybeMockedDeep as M, SpyInstance as S, MaybeMocked as a, MaybePartiallyMocked as b, MaybePartiallyMockedDeep as c, suite as d, describe as e, fn as f, bench as g, beforeAll as h, it as i, afterAll as j, beforeEach as k, afterEach as l, globalExpect as m, createExpect as n, onTestFailed as o, expectTypeOf as p, ExpectTypeOf as q, assertType as r, spyOn as s, test as t, MockedFunction as u, MockedObject as v, MockInstance as w, Mock as x, MockContext as y, Mocked as z }; diff --git a/node_modules/vitest/dist/index.d.ts b/node_modules/vitest/dist/index.d.ts new file mode 100644 index 0000000..9afd22e --- /dev/null +++ b/node_modules/vitest/dist/index.d.ts @@ -0,0 +1,207 @@ +import { s as spyOn, f as fn, M as MaybeMockedDeep, a as MaybeMocked, b as MaybePartiallyMocked, c as MaybePartiallyMockedDeep, E as EnhancedSpy } from './index-2d10c3fd.js'; +export { A as AssertType, E as EnhancedSpy, q as ExpectTypeOf, x as Mock, y as MockContext, w as MockInstance, z as Mocked, B as MockedClass, u as MockedFunction, v as MockedObject, S as SpyInstance, j as afterAll, l as afterEach, r as assertType, h as beforeAll, k as beforeEach, g as bench, n as createExpect, e as describe, m as expect, p as expectTypeOf, i as it, o as onTestFailed, d as suite, t as test } from './index-2d10c3fd.js'; +import { D as DoneCallback, F as FakeTimerInstallOpts, M as MockFactoryWithHelper, R as RuntimeConfig, a as File, T as TaskResultPack, b as ResolvedConfig, c as ModuleGraphData, d as Reporter } from './types-e1e1d1e5.js'; +export { a1 as AfterSuiteRunMeta, A as ApiConfig, a7 as ArgumentsType, a6 as Arrayable, a4 as Awaitable, ao as BaseCoverageOptions, au as BenchFunction, as as Benchmark, av as BenchmarkAPI, at as BenchmarkResult, ar as BenchmarkUserOptions, B as BuiltinEnvironment, j as CSSModuleScopeStrategy, C as CollectLineNumbers, g as CollectLines, ab as Constructable, i as Context, aq as CoverageC8Options, ap as CoverageIstanbulOptions, am as CoverageOptions, aj as CoverageProvider, ak as CoverageProviderModule, al as CoverageReporter, a9 as DeepMerge, D as DoneCallback, ae as Environment, E as EnvironmentOptions, ad as EnvironmentReturn, ah as ErrorWithDiff, a as File, x as HookCleanupCallback, H as HookListener, I as InlineConfig, J as JSDOMOptions, a8 as MergeInsertions, ac as ModuleCache, c as ModuleGraphData, aa as MutableArray, a5 as Nullable, ai as OnServerRestartHandler, O as OnTestFailedHandler, ag as ParsedStack, e as RawErrsMap, d as Reporter, a0 as ResolveIdFunction, b as ResolvedConfig, an as ResolvedCoverageOptions, h as RootAndTarget, m as RunMode, R as RuntimeConfig, K as RuntimeContext, S as SequenceHooks, P as SnapshotData, X as SnapshotMatchOptions, Y as SnapshotResult, W as SnapshotStateOptions, _ as SnapshotSummary, Q as SnapshotUpdateState, q as Suite, w as SuiteAPI, z as SuiteCollector, G as SuiteFactory, y as SuiteHooks, s as Task, o as TaskBase, p as TaskResult, T as TaskResultPack, n as TaskState, r as Test, v as TestAPI, L as TestContext, t as TestFunction, u as TestOptions, f as TscErrorInfo, l as TypecheckConfig, Z as UncheckedSnapshot, U as UserConfig, af as UserConsoleLog, N as Vitest, V as VitestEnvironment, k as VitestRunMode, $ as WorkerContext, a3 as WorkerGlobalState, a2 as WorkerRPC } from './types-e1e1d1e5.js'; +import { TransformResult } from 'vite'; +import * as chai from 'chai'; +export { chai }; +export { assert, should } from 'chai'; +export { Bench as BenchFactory, Options as BenchOptions, Task as BenchTask, TaskResult as BenchTaskResult } from 'tinybench'; +import 'tinyspy'; +import 'vite-node/client'; +import 'vite-node/server'; +import 'vite-node'; +import 'node:fs'; +import 'node:worker_threads'; + +/** + * A simple wrapper for converting callback style to promise + */ +declare function withCallback(fn: (done: DoneCallback) => void): Promise; + +/** + * This utils allows computational intensive tasks to only be ran once + * across test reruns to improve the watch mode performance. + * + * Currently only works with `isolate: false` + * + * @experimental + */ +declare function runOnce(fn: (() => T), key?: string): T; +/** + * Get a boolean indicates whether the task is running in the first time. + * Could only be `false` in watch mode. + * + * Currently only works with `isolate: false` + * + * @experimental + */ +declare function isFirstRun(): boolean; + +declare class VitestUtils { + private _timers; + private _mockedDate; + private _mocker; + constructor(); + useFakeTimers(config?: FakeTimerInstallOpts): this; + useRealTimers(): this; + runOnlyPendingTimers(): this; + runAllTimers(): this; + runAllTicks(): this; + advanceTimersByTime(ms: number): this; + advanceTimersToNextTimer(): this; + getTimerCount(): number; + setSystemTime(time: number | string | Date): this; + getMockedSystemTime(): string | number | Date | null; + getRealSystemTime(): number; + clearAllTimers(): this; + spyOn: typeof spyOn; + fn: typeof fn; + private getImporter; + /** + * Makes all `imports` to passed module to be mocked. + * - If there is a factory, will return it's result. The call to `vi.mock` is hoisted to the top of the file, + * so you don't have access to variables declared in the global file scope, if you didn't put them before imports! + * - If `__mocks__` folder with file of the same name exist, all imports will + * return it. + * - If there is no `__mocks__` folder or a file with the same name inside, will call original + * module and mock it. + * @param path Path to the module. Can be aliased, if your config supports it + * @param factory Factory for the mocked module. Has the highest priority. + */ + mock(path: string, factory?: MockFactoryWithHelper): void; + /** + * Removes module from mocked registry. All subsequent calls to import will + * return original module even if it was mocked. + * @param path Path to the module. Can be aliased, if your config supports it + */ + unmock(path: string): void; + doMock(path: string, factory?: () => any): void; + doUnmock(path: string): void; + /** + * Imports module, bypassing all checks if it should be mocked. + * Can be useful if you want to mock module partially. + * @example + * vi.mock('./example', async () => { + * const axios = await vi.importActual('./example') + * + * return { ...axios, get: vi.fn() } + * }) + * @param path Path to the module. Can be aliased, if your config supports it + * @returns Actual module without spies + */ + importActual(path: string): Promise; + /** + * Imports a module with all of its properties and nested properties mocked. + * For the rules applied, see docs. + * @param path Path to the module. Can be aliased, if your config supports it + * @returns Fully mocked module + */ + importMock(path: string): Promise>; + /** + * Type helpers for TypeScript. In reality just returns the object that was passed. + * + * When `partial` is `true` it will expect a `Partial` as a return value. + * @example + * import example from './example' + * vi.mock('./example') + * + * test('1+1 equals 2' async () => { + * vi.mocked(example.calc).mockRestore() + * + * const res = example.calc(1, '+', 1) + * + * expect(res).toBe(2) + * }) + * @param item Anything that can be mocked + * @param deep If the object is deeply mocked + * @param options If the object is partially or deeply mocked + */ + mocked(item: T, deep?: false): MaybeMocked; + mocked(item: T, deep: true): MaybeMockedDeep; + mocked(item: T, options: { + partial?: false; + deep?: false; + }): MaybeMocked; + mocked(item: T, options: { + partial?: false; + deep: true; + }): MaybeMockedDeep; + mocked(item: T, options: { + partial: true; + deep?: false; + }): MaybePartiallyMocked; + mocked(item: T, options: { + partial: true; + deep: true; + }): MaybePartiallyMockedDeep; + isMockFunction(fn: any): fn is EnhancedSpy; + clearAllMocks(): this; + resetAllMocks(): this; + restoreAllMocks(): this; + private _stubsGlobal; + private _stubsEnv; + /** + * Makes value available on global namespace. + * Useful, if you want to have global variables available, like `IntersectionObserver`. + * You can return it back to original value with `vi.unstubGlobals`, or by enabling `unstubGlobals` config option. + */ + stubGlobal(name: string | symbol | number, value: any): this; + /** + * Changes the value of `import.meta.env` and `process.env`. + * You can return it back to original value with `vi.unstubEnvs`, or by enabling `unstubEnvs` config option. + */ + stubEnv(name: string, value: string): this; + /** + * Reset the value to original value that was available before first `vi.stubGlobal` was called. + */ + unstubAllGlobals(): this; + /** + * Reset enviromental variables to the ones that were available before first `vi.stubEnv` was called. + */ + unstubAllEnvs(): this; + resetModules(): this; + /** + * Wait for all imports to load. Useful, if you have a synchronous call that starts + * importing a module that you cannot await otherwise. + * Will also wait for new imports, started during the wait. + */ + dynamicImportSettled(): Promise; + private _config; + /** + * Updates runtime config. You can only change values that are used when executing tests. + */ + setConfig(config: RuntimeConfig): void; + /** + * If config was changed with `vi.setConfig`, this will reset it to the original state. + */ + resetConfig(): void; +} +declare const vitest: VitestUtils; +declare const vi: VitestUtils; + +declare function getRunningMode(): "run" | "watch"; +declare function isWatchMode(): boolean; + +interface TransformResultWithSource extends TransformResult { + source?: string; +} +interface WebSocketHandlers { + onWatcherStart: () => Promise; + onFinished(files?: File[]): Promise; + onCollected(files?: File[]): Promise; + onTaskUpdate(packs: TaskResultPack[]): void; + getFiles(): File[]; + getPaths(): Promise; + getConfig(): ResolvedConfig; + getModuleGraph(id: string): Promise; + getTransformResult(id: string): Promise; + readFile(id: string): Promise; + writeFile(id: string, content: string): Promise; + rerun(files: string[]): Promise; + updateSnapshot(file?: File): Promise; +} +interface WebSocketEvents extends Pick { +} + +export { TransformResultWithSource, WebSocketEvents, WebSocketHandlers, getRunningMode, isFirstRun, isWatchMode, runOnce, vi, vitest, withCallback }; diff --git a/node_modules/vitest/dist/index.js b/node_modules/vitest/dist/index.js new file mode 100644 index 0000000..8b21334 --- /dev/null +++ b/node_modules/vitest/dist/index.js @@ -0,0 +1,27 @@ +export { b as bench, c as createExpect, d as describe, e as expect, i as it, s as suite, t as test } from './chunk-runtime-chain.6df5a66b.js'; +import { e as dist } from './chunk-utils-import.2baa69a9.js'; +export { a as afterAll, d as afterEach, f as assertType, b as beforeAll, c as beforeEach, k as getRunningMode, h as isFirstRun, l as isWatchMode, o as onTestFailed, g as runOnce, v as vi, j as vitest, w as withCallback } from './chunk-utils-import.2baa69a9.js'; +import * as chai from 'chai'; +export { chai }; +export { assert, should } from 'chai'; +import 'util'; +import './chunk-mock-date.a1c85759.js'; +import 'node:path'; +import 'picocolors'; +import 'local-pkg'; +import './chunk-utils-env.b861e3a0.js'; +import 'node:url'; +import 'path'; +import './vendor-_commonjsHelpers.addc3445.js'; +import './chunk-utils-timers.52534f96.js'; +import './vendor-index.723a074f.js'; +import 'tinyspy'; +import './chunk-utils-source-map.60562959.js'; +import './chunk-runtime-rpc.7f83c8a9.js'; +import 'node:fs'; +import 'fs'; + + + +var expectTypeOf = dist.expectTypeOf; +export { expectTypeOf }; diff --git a/node_modules/vitest/dist/loader.js b/node_modules/vitest/dist/loader.js new file mode 100644 index 0000000..38df547 --- /dev/null +++ b/node_modules/vitest/dist/loader.js @@ -0,0 +1,98 @@ +import { pathToFileURL } from 'node:url'; +import { readFile } from 'node:fs/promises'; +import { i as isNodeBuiltin, h as hasCJSSyntax } from './vendor-index.2e96c50b.js'; +import { normalizeModuleId } from 'vite-node/utils'; +import { g as getWorkerState } from './chunk-mock-date.a1c85759.js'; +import 'acorn'; +import 'node:module'; +import 'node:fs'; +import 'url'; +import 'fs'; +import 'path'; +import 'module'; +import 'assert'; +import 'util'; +import 'node:path'; +import 'picocolors'; +import 'local-pkg'; +import './chunk-utils-env.b861e3a0.js'; + +var ModuleFormat = /* @__PURE__ */ ((ModuleFormat2) => { + ModuleFormat2["Builtin"] = "builtin"; + ModuleFormat2["Commonjs"] = "commonjs"; + ModuleFormat2["Json"] = "json"; + ModuleFormat2["Module"] = "module"; + ModuleFormat2["Wasm"] = "wasm"; + return ModuleFormat2; +})(ModuleFormat || {}); + +const ESM_RE = /([\s;}]|^)(import[\w,{}\s*]*from|import\s*['"*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m; +function hasESMSyntax(code) { + return ESM_RE.test(code); +} +const cache = /* @__PURE__ */ new Map(); +const getPotentialSource = async (filepath, result) => { + var _a; + if (!result.url.startsWith("file://") || result.format === "module") + return null; + let source = (_a = cache.get(result.url)) == null ? void 0 : _a.source; + if (source == null) + source = await readFile(filepath, "utf8"); + return source; +}; +const detectESM = (url, source) => { + const cached = cache.get(url); + if (cached) + return cached.isPseudoESM; + if (!source) + return false; + return hasESMSyntax(source) && !hasCJSSyntax(source); +}; +const resolve = async (url, context, next) => { + const { parentURL } = context; + const state = getWorkerState(); + const resolver = state == null ? void 0 : state.rpc.resolveId; + if (!parentURL || isNodeBuiltin(url) || !resolver) + return next(url, context, next); + const id = normalizeModuleId(url); + const importer = normalizeModuleId(parentURL); + const resolved = await resolver(id, importer); + let result; + let filepath; + if (resolved) { + const resolvedUrl = pathToFileURL(resolved.id).toString(); + filepath = resolved.id; + result = { + url: resolvedUrl, + shortCircuit: true + }; + } else { + const { url: resolvedUrl, format } = await next(url, context, next); + filepath = new URL(resolvedUrl).pathname; + result = { + url: resolvedUrl, + format, + shortCircuit: true + }; + } + const source = await getPotentialSource(filepath, result); + const isPseudoESM = detectESM(result.url, source); + if (typeof source === "string") + cache.set(result.url, { isPseudoESM, source }); + if (isPseudoESM) + result.format = ModuleFormat.Module; + return result; +}; +const load = async (url, context, next) => { + const result = await next(url, context, next); + const cached = cache.get(url); + if ((cached == null ? void 0 : cached.isPseudoESM) && result.format !== "module") { + return { + source: cached.source, + format: ModuleFormat.Module + }; + } + return result; +}; + +export { load, resolve }; diff --git a/node_modules/vitest/dist/node.d.ts b/node_modules/vitest/dist/node.d.ts new file mode 100644 index 0000000..e48a686 --- /dev/null +++ b/node_modules/vitest/dist/node.d.ts @@ -0,0 +1,72 @@ +import { k as VitestRunMode, U as UserConfig, N as Vitest, aw as MockFactory, ax as MockMap, ay as TestSequencer } from './types-e1e1d1e5.js'; +export { ay as TestSequencer, aA as TestSequencerConstructor, N as Vitest, az as startVitest } from './types-e1e1d1e5.js'; +import { UserConfig as UserConfig$1, Plugin } from 'vite'; +import { ViteNodeRunner } from 'vite-node/client'; +import { ViteNodeRunnerOptions } from 'vite-node'; +import 'tinybench'; +import 'vite-node/server'; +import 'node:fs'; +import 'node:worker_threads'; + +declare function createVitest(mode: VitestRunMode, options: UserConfig, viteOverrides?: UserConfig$1): Promise; + +declare function VitestPlugin(options?: UserConfig, ctx?: Vitest): Promise; + +type Key = string | symbol; +declare class VitestMocker { + runner: VitestRunner; + private static pendingIds; + private static spyModulePath; + private static spyModule?; + private resolveCache; + constructor(runner: VitestRunner); + private get root(); + private get base(); + private get mockMap(); + private get moduleCache(); + getSuiteFilepath(): string; + getMocks(): { + [x: string]: string | MockFactory | null; + }; + private resolvePath; + private resolveMocks; + private callFunctionMock; + getMockPath(dep: string): string; + getDependencyMock(id: string): string | MockFactory | null; + normalizePath(path: string): string; + resolveMockPath(mockPath: string, external: string | null): string | null; + mockObject(object: Record, mockExports?: Record): Record; + unmockPath(path: string): void; + mockPath(originalId: string, path: string, external: string | null, factory?: MockFactory): void; + importActual(rawId: string, importee: string): Promise; + importMock(rawId: string, importee: string): Promise; + initializeSpyModule(): Promise; + requestWithMock(url: string, callstack: string[]): Promise; + queueMock(id: string, importer: string, factory?: MockFactory): void; + queueUnmock(id: string, importer: string): void; +} + +interface ExecuteOptions extends ViteNodeRunnerOptions { + mockMap: MockMap; +} +declare class VitestRunner extends ViteNodeRunner { + options: ExecuteOptions; + mocker: VitestMocker; + constructor(options: ExecuteOptions); + shouldResolveId(id: string, _importee?: string | undefined): boolean; + resolveUrl(id: string, importee?: string): Promise<[url: string, fsPath: string]>; + dependencyRequest(id: string, fsPath: string, callstack: string[]): Promise; + prepareContext(context: Record): Record & { + __vitest_mocker__: VitestMocker; + }; + shouldInterop(path: string, mod: any): boolean; +} + +declare class BaseSequencer implements TestSequencer { + protected ctx: Vitest; + constructor(ctx: Vitest); + shard(files: string[]): Promise; + sort(files: string[]): Promise; +} + +export { BaseSequencer, ExecuteOptions, VitestPlugin, VitestRunner, createVitest }; diff --git a/node_modules/vitest/dist/node.js b/node_modules/vitest/dist/node.js new file mode 100644 index 0000000..6184e1f --- /dev/null +++ b/node_modules/vitest/dist/node.js @@ -0,0 +1,53 @@ +export { B as BaseSequencer, V as VitestPlugin, c as createVitest, s as startVitest } from './chunk-snapshot-manager.700322bf.js'; +export { V as VitestRunner } from './chunk-runtime-mocker.a677dd28.js'; +import './chunk-utils-env.b861e3a0.js'; +import 'node:url'; +import 'path'; +import './chunk-integrations-coverage.44413252.js'; +import 'local-pkg'; +import './chunk-env-node.b3664da2.js'; +import 'node:console'; +import './chunk-mock-date.a1c85759.js'; +import 'node:path'; +import 'picocolors'; +import 'vite'; +import 'node:process'; +import 'node:fs'; +import 'os'; +import 'util'; +import 'stream'; +import 'events'; +import 'fs'; +import './vendor-_commonjsHelpers.addc3445.js'; +import 'vite-node/client'; +import 'vite-node/server'; +import 'node:fs/promises'; +import './vendor-index.b2fdde54.js'; +import 'node:buffer'; +import 'node:child_process'; +import './vendor-index.7a2cebfe.js'; +import 'child_process'; +import 'assert'; +import 'buffer'; +import 'node:os'; +import 'source-map'; +import 'module'; +import 'acorn'; +import 'acorn-walk'; +import 'node:worker_threads'; +import 'tinypool'; +import './vendor-index.783e7f3e.js'; +import 'perf_hooks'; +import './chunk-utils-source-map.60562959.js'; +import './chunk-utils-timers.52534f96.js'; +import 'crypto'; +import 'vite-node/utils'; +import './vendor-index.9c919048.js'; +import 'node:crypto'; +import './chunk-magic-string.3a794426.js'; +import 'strip-literal'; +import 'readline'; +import './vendor-index.9f20a9be.js'; +import './vendor-index.2e96c50b.js'; +import 'node:module'; +import 'url'; diff --git a/node_modules/vitest/dist/spy.js b/node_modules/vitest/dist/spy.js new file mode 100644 index 0000000..9695537 --- /dev/null +++ b/node_modules/vitest/dist/spy.js @@ -0,0 +1,2 @@ +export { f as fn, i as isMockFunction, a as spies, s as spyOn } from './vendor-index.723a074f.js'; +import 'tinyspy'; diff --git a/node_modules/vitest/dist/suite.js b/node_modules/vitest/dist/suite.js new file mode 100644 index 0000000..52d2db3 --- /dev/null +++ b/node_modules/vitest/dist/suite.js @@ -0,0 +1,18 @@ +import 'util'; +import 'chai'; +import './chunk-mock-date.a1c85759.js'; +export { b as bench, f as clearCollectorContext, r as createSuiteHooks, h as defaultSuite, d as describe, g as getCurrentSuite, i as it, s as suite, t as test } from './chunk-runtime-chain.6df5a66b.js'; +import 'node:path'; +import 'picocolors'; +import 'local-pkg'; +import './chunk-utils-env.b861e3a0.js'; +import 'node:url'; +import 'path'; +import './vendor-_commonjsHelpers.addc3445.js'; +import './chunk-utils-timers.52534f96.js'; +import './vendor-index.723a074f.js'; +import 'tinyspy'; +import './chunk-utils-source-map.60562959.js'; +import './chunk-runtime-rpc.7f83c8a9.js'; +import 'node:fs'; +import 'fs'; diff --git a/node_modules/vitest/dist/types-e1e1d1e5.d.ts b/node_modules/vitest/dist/types-e1e1d1e5.d.ts new file mode 100644 index 0000000..1134abf --- /dev/null +++ b/node_modules/vitest/dist/types-e1e1d1e5.d.ts @@ -0,0 +1,2260 @@ +import { UserConfig as UserConfig$1, ViteDevServer, CommonServerOptions, AliasOptions } from 'vite'; +import { Task as Task$1, TaskResult as TaskResult$1, Bench, Options } from 'tinybench'; +import { ViteNodeRunner } from 'vite-node/client'; +import { ViteNodeServer } from 'vite-node/server'; +import { RawSourceMap, ViteNodeResolveId, FetchFunction, ModuleCacheMap } from 'vite-node'; +import { Stats } from 'node:fs'; +import { MessagePort } from 'node:worker_threads'; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +declare type Colors = { + comment: { + close: string; + open: string; + }; + content: { + close: string; + open: string; + }; + prop: { + close: string; + open: string; + }; + tag: { + close: string; + open: string; + }; + value: { + close: string; + open: string; + }; +}; +declare type Indent = (arg0: string) => string; +declare type Refs = Array; +declare type Print = (arg0: unknown) => string; +declare type ThemeReceived = { + comment?: string; + content?: string; + prop?: string; + tag?: string; + value?: string; +}; +declare type CompareKeys = ((a: string, b: string) => number) | undefined; +interface PrettyFormatOptions { + callToJSON?: boolean; + compareKeys?: CompareKeys; + escapeRegex?: boolean; + escapeString?: boolean; + highlight?: boolean; + indent?: number; + maxDepth?: number; + min?: boolean; + plugins?: Plugins; + printBasicPrototype?: boolean; + printFunctionName?: boolean; + theme?: ThemeReceived; +} +declare type OptionsReceived = PrettyFormatOptions; +declare type Config = { + callToJSON: boolean; + compareKeys: CompareKeys; + colors: Colors; + escapeRegex: boolean; + escapeString: boolean; + indent: string; + maxDepth: number; + min: boolean; + plugins: Plugins; + printBasicPrototype: boolean; + printFunctionName: boolean; + spacingInner: string; + spacingOuter: string; +}; +declare type Printer = (val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string; +declare type Test$1 = (arg0: any) => boolean; +declare type NewPlugin = { + serialize: (val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string; + test: Test$1; +}; +declare type PluginOptions = { + edgeSpacing: string; + min: boolean; + spacing: string; +}; +declare type OldPlugin = { + print: (val: unknown, print: Print, indent: Indent, options: PluginOptions, colors: Colors) => string; + test: Test$1; +}; +declare type Plugin = NewPlugin | OldPlugin; +declare type Plugins = Array; + +// Type definitions for @sinonjs/fake-timers 8.1 +// Project: https://github.com/sinonjs/fake-timers +// Definitions by: Wim Looman +// Rogier Schouten +// Yishai Zehavi +// Remco Haszing +// Jaden Simon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/** + * Names of clock methods that may be faked by install. + */ +type FakeMethod = + | 'setTimeout' + | 'clearTimeout' + | 'setImmediate' + | 'clearImmediate' + | 'setInterval' + | 'clearInterval' + | 'Date' + | 'nextTick' + | 'hrtime' + | 'requestAnimationFrame' + | 'cancelAnimationFrame' + | 'requestIdleCallback' + | 'cancelIdleCallback' + | 'performance' + | 'queueMicrotask'; + +interface FakeTimerInstallOpts { + /** + * Installs fake timers with the specified unix epoch (default: 0) + */ + now?: number | Date | undefined; + + /** + * An array with names of global methods and APIs to fake. By default, `@sinonjs/fake-timers` does not replace `nextTick()` and `queueMicrotask()`. + * For instance, `FakeTimers.install({ toFake: ['setTimeout', 'nextTick'] })` will fake only `setTimeout()` and `nextTick()` + */ + toFake?: FakeMethod[] | undefined; + + /** + * The maximum number of timers that will be run when calling runAll() (default: 1000) + */ + loopLimit?: number | undefined; + + /** + * Tells @sinonjs/fake-timers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by + * 20ms for every 20ms change in the real system time) (default: false) + */ + shouldAdvanceTime?: boolean | undefined; + + /** + * Relevant only when using with shouldAdvanceTime: true. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change + * in the real system time (default: 20) + */ + advanceTimeDelta?: number | undefined; + + /** + * Tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their respective handlers. These are not cleared by + * default, leading to potentially unexpected behavior if timers existed prior to installing FakeTimers. (default: false) + */ + shouldClearNativeTimers?: boolean | undefined; +} + +declare class SnapshotManager { + options: SnapshotStateOptions; + summary: SnapshotSummary; + extension: string; + constructor(options: SnapshotStateOptions); + clear(): void; + add(result: SnapshotResult): void; + resolvePath(testPath: string): string; +} + +interface ParsedFile extends File { + start: number; + end: number; +} +interface ParsedTest extends Test { + start: number; + end: number; +} +interface ParsedSuite extends Suite { + start: number; + end: number; +} +interface LocalCallDefinition { + start: number; + end: number; + name: string; + type: 'suite' | 'test'; + mode: 'run' | 'skip' | 'only' | 'todo'; + task: ParsedSuite | ParsedFile | ParsedTest; +} +interface FileInformation { + file: File; + filepath: string; + parsed: string; + map: RawSourceMap | null; + definitions: LocalCallDefinition[]; +} + +declare class TypeCheckError extends Error { + message: string; + stacks: ParsedStack[]; + name: string; + constructor(message: string, stacks: ParsedStack[]); +} +interface ErrorsCache { + files: File[]; + sourceErrors: TypeCheckError[]; +} +type Callback = []> = (...args: Args) => Awaitable; +declare class Typechecker { + protected ctx: Vitest; + protected files: string[]; + private _onParseStart?; + private _onParseEnd?; + private _onWatcherRerun?; + private _result; + private _tests; + private tempConfigPath?; + private allowJs?; + private process; + constructor(ctx: Vitest, files: string[]); + onParseStart(fn: Callback): void; + onParseEnd(fn: Callback<[ErrorsCache]>): void; + onWatcherRerun(fn: Callback): void; + protected collectFileTests(filepath: string): Promise; + protected getFiles(): string[]; + collectTests(): Promise>; + protected prepareResults(output: string): Promise<{ + files: File[]; + sourceErrors: TypeCheckError[]; + }>; + protected parseTscLikeOutput(output: string): Promise>; + clear(): Promise; + stop(): Promise; + protected ensurePackageInstalled(root: string, checker: string): Promise; + prepare(): Promise; + start(): Promise; + getResult(): ErrorsCache; + getTestFiles(): File[]; + getTestPacks(): TaskResultPack[]; +} + +type RunWithFiles = (files: string[], invalidates?: string[]) => Promise; +interface WorkerPool { + runTests: RunWithFiles; + close: () => Promise; +} + +interface CollectingPromise { + promise: Promise; + resolve: () => void; +} +declare class StateManager { + filesMap: Map; + pathsSet: Set; + collectingPromise: CollectingPromise | undefined; + idMap: Map; + taskFileMap: WeakMap; + errorsSet: Set; + catchError(err: unknown, type: string): void; + clearErrors(): void; + getUnhandledErrors(): unknown[]; + startCollectingPaths(): void; + finishCollectingPaths(): void; + getPaths(): Promise; + getFiles(keys?: string[]): File[]; + getFilepaths(): string[]; + getFailedFilepaths(): string[]; + collectPaths(paths?: string[]): void; + collectFiles(files?: File[]): void; + clearFiles(paths?: string[]): void; + updateId(task: Task): void; + updateTasks(packs: TaskResultPack[]): void; + updateUserLog(log: UserConsoleLog): void; +} + +declare class Logger { + ctx: Vitest; + console: Console; + outputStream: NodeJS.WriteStream & { + fd: 1; + }; + errorStream: NodeJS.WriteStream & { + fd: 2; + }; + logUpdate: ((...text: string[]) => void) & { + clear(): void; + done(): void; + }; + private _clearScreenPending; + constructor(ctx: Vitest, console?: Console); + log(...args: any[]): void; + error(...args: any[]): void; + warn(...args: any[]): void; + clearFullScreen(message: string): void; + clearScreen(message: string, force?: boolean): void; + private _clearScreen; + printError(err: unknown, fullStack?: boolean, type?: string): Promise; + printNoTestFound(filters?: string[]): void; + printBanner(): void; + printUnhandledErrors(errors: unknown[]): Promise; + printSourceTypeErrors(errors: TypeCheckError[]): Promise; +} + +interface SuiteResultCache { + failed: boolean; + duration: number; +} +declare class ResultsCache { + private cache; + private cachePath; + private version; + private root; + getCachePath(): string | null; + setConfig(root: string, config: ResolvedConfig['cache']): void; + getResults(fsPath: string): SuiteResultCache | undefined; + readFromCache(): Promise; + updateResults(files: File[]): void; + removeFromCache(filepath: string): void; + writeToCache(): Promise; +} + +interface CliOptions extends UserConfig { + /** + * Override the watch mode + */ + run?: boolean; +} +/** + * Start Vitest programmatically + * + * Returns a Vitest instance if initialized successfully. + */ +declare function startVitest(mode: VitestRunMode, cliFilters: string[], options: CliOptions, viteOverrides?: UserConfig$1): Promise; + +type FileStatsCache = Pick; +declare class FilesStatsCache { + cache: Map; + getStats(fsPath: string): FileStatsCache | undefined; + updateStats(fsPath: string): Promise; + removeStats(fsPath: string): void; +} + +declare class VitestCache { + results: ResultsCache; + stats: FilesStatsCache; + getFileTestResults(id: string): SuiteResultCache | undefined; + getFileStats(id: string): { + size: number; + } | undefined; + static resolveCacheDir(root: string, dir: string | undefined): string; + static clearCache(options: CliOptions): Promise<{ + dir: string; + cleared: boolean; + }>; +} + +declare class Vitest { + readonly mode: VitestRunMode; + config: ResolvedConfig; + configOverride: Partial | undefined; + server: ViteDevServer; + state: StateManager; + snapshot: SnapshotManager; + cache: VitestCache; + reporters: Reporter[]; + coverageProvider: CoverageProvider | null | undefined; + logger: Logger; + pool: WorkerPool | undefined; + typechecker: Typechecker | undefined; + vitenode: ViteNodeServer; + invalidates: Set; + changedTests: Set; + runningPromise?: Promise; + closingPromise?: Promise; + isFirstRun: boolean; + restartsCount: number; + runner: ViteNodeRunner; + constructor(mode: VitestRunMode); + private _onRestartListeners; + private _onSetServer; + setServer(options: UserConfig, server: ViteDevServer): Promise; + initCoverageProvider(): Promise; + getSerializableConfig(): ResolvedConfig; + typecheck(filters?: string[]): Promise; + start(filters?: string[]): Promise; + private getTestDependencies; + filterTestsBySource(tests: string[]): Promise; + runFiles(paths: string[]): Promise; + rerunFiles(files?: string[], trigger?: string): Promise; + changeNamePattern(pattern: string, files?: string[], trigger?: string): Promise; + changeFilenamePattern(pattern: string): Promise; + rerunFailed(): Promise; + updateSnapshot(files?: string[]): Promise; + private _rerunTimer; + private scheduleRerun; + private unregisterWatcher; + private registerWatcher; + /** + * @returns A value indicating whether rerun is needed (changedTests was mutated) + */ + private handleFileChanged; + close(): Promise; + /** + * Close the thread pool and exit the process + */ + exit(force?: boolean): Promise; + report(name: T, ...args: ArgumentsType$1): Promise; + globFiles(filters: string[], include: string[], exclude: string[]): Promise; + globTestFiles(filters?: string[]): Promise; + isTargetFile(id: string, source?: string): Promise; + isInSourceTestFile(code: string): boolean; + onServerRestart(fn: OnServerRestartHandler): void; + onAfterSetServer(fn: OnServerRestartHandler): void; +} + +type MockFactoryWithHelper = (importOriginal: () => Promise) => any; +type MockFactory = () => any; +type MockMap = Map>; + +interface TestSequencer { + /** + * Slicing tests into shards. Will be run before `sort`. + * Only run, if `shard` is defined. + */ + shard(files: string[]): Awaitable; + sort(files: string[]): Awaitable; +} +interface TestSequencerConstructor { + new (ctx: Vitest): TestSequencer; +} + +declare abstract class BaseReporter implements Reporter { + start: number; + end: number; + watchFilters?: string[]; + isTTY: false; + ctx: Vitest; + private _filesInWatchMode; + private _lastRunTimeout; + private _lastRunTimer; + private _lastRunCount; + private _timeStart; + constructor(); + get mode(): VitestRunMode; + onInit(ctx: Vitest): void; + relative(path: string): string; + onFinished(files?: File[], errors?: unknown[]): Promise; + onTaskUpdate(packs: TaskResultPack[]): void; + onWatcherStart(files?: File[], errors?: unknown[]): Promise; + private resetLastRunLog; + onWatcherRerun(files: string[], trigger?: string): Promise; + onUserConsoleLog(log: UserConsoleLog): void; + shouldLog(log: UserConsoleLog): boolean; + onServerRestart(reason?: string): void; + reportSummary(files: File[]): Promise; + reportTestSummary(files: File[]): Promise; + private printErrorsSummary; + reportBenchmarkSummary(files: File[]): Promise; + private printTaskErrors; + registerUnhandledRejection(): void; +} + +interface ListRendererOptions$1 { + renderSucceed?: boolean; + logger: Logger; + showHeap: boolean; + mode: VitestRunMode; +} +declare const createListRenderer: (_tasks: Task[], options: ListRendererOptions$1) => { + start(): any; + update(_tasks: Task[]): any; + stop(): Promise; + clear(): void; +}; + +declare class DefaultReporter extends BaseReporter { + renderer?: ReturnType; + rendererOptions: ListRendererOptions$1; + onTestRemoved(trigger?: string): Promise; + onCollected(): void; + onFinished(files?: File[], errors?: unknown[]): Promise; + onWatcherStart(files?: File[], errors?: unknown[]): Promise; + stopListRender(): Promise; + onWatcherRerun(files: string[], trigger?: string): Promise; + onUserConsoleLog(log: UserConsoleLog): void; +} + +declare class DotReporter extends BaseReporter { + renderer?: ReturnType; + onCollected(): void; + onFinished(files?: File[], errors?: unknown[]): Promise; + onWatcherStart(): Promise; + stopListRender(): Promise; + onWatcherRerun(files: string[], trigger?: string): Promise; + onUserConsoleLog(log: UserConsoleLog): void; +} + +interface Callsite { + line: number; + column: number; +} +declare class JsonReporter$1 implements Reporter { + start: number; + ctx: Vitest; + onInit(ctx: Vitest): void; + protected logTasks(files: File[]): Promise; + onFinished(files?: File[]): Promise; + /** + * Writes the report to an output file if specified in the config, + * or logs it to the console otherwise. + * @param report + */ + writeReport(report: string): Promise; + protected getFailureLocation(test: Task): Promise; +} + +declare class VerboseReporter extends DefaultReporter { + constructor(); + onTaskUpdate(packs: TaskResultPack[]): void; +} + +declare class TapReporter implements Reporter { + protected ctx: Vitest; + private logger; + onInit(ctx: Vitest): void; + static getComment(task: Task): string; + private logErrorDetails; + protected logTasks(tasks: Task[]): void; + onFinished(files?: File[]): Promise; +} + +declare class JUnitReporter implements Reporter { + private ctx; + private reportFile?; + private baseLog; + private logger; + private _timeStart; + onInit(ctx: Vitest): Promise; + writeElement(name: string, attrs: Record, children: () => Promise): Promise; + writeErrorDetails(error: ErrorWithDiff): Promise; + writeLogs(task: Task, type: 'err' | 'out'): Promise; + writeTasks(tasks: Task[], filename: string): Promise; + onFinished(files?: File[]): Promise; +} + +declare class TapFlatReporter extends TapReporter { + onInit(ctx: Vitest): void; + onFinished(files?: File[]): Promise; +} + +declare class JsonReporter implements Reporter { + start: number; + ctx: Vitest; + onInit(ctx: Vitest): void; + protected logTasks(files: File[]): Promise; + onFinished(files?: File[]): Promise; + /** + * Writes the report to an output file if specified in the config, + * or logs it to the console otherwise. + * @param report + */ + writeReport(report: string): Promise; +} + +interface ListRendererOptions { + renderSucceed?: boolean; + logger: Logger; + showHeap: boolean; +} +declare const createTableRenderer: (_tasks: Task[], options: ListRendererOptions) => { + start(): any; + update(_tasks: Task[]): any; + stop(): Promise; + clear(): void; +}; + +declare class TableReporter extends BaseReporter { + renderer?: ReturnType; + rendererOptions: ListRendererOptions$1; + onTestRemoved(trigger?: string): Promise; + onCollected(): void; + onFinished(files?: File[], errors?: unknown[]): Promise; + onWatcherStart(): Promise; + stopListRender(): Promise; + onWatcherRerun(files: string[], trigger?: string): Promise; + onUserConsoleLog(log: UserConsoleLog): void; +} + +declare const BenchmarkReportsMap: { + default: typeof TableReporter; + verbose: typeof VerboseReporter; + json: typeof JsonReporter; +}; +type BenchmarkBuiltinReporters = keyof typeof BenchmarkReportsMap; + +declare const ReportersMap: { + default: typeof DefaultReporter; + verbose: typeof VerboseReporter; + dot: typeof DotReporter; + json: typeof JsonReporter$1; + tap: typeof TapReporter; + 'tap-flat': typeof TapFlatReporter; + junit: typeof JUnitReporter; +}; +type BuiltinReporters = keyof typeof ReportersMap; + +interface RollupError extends RollupLogProps { + parserError?: Error; + stack?: string; + watchFiles?: string[]; +} + +interface RollupWarning extends RollupLogProps { + chunkName?: string; + cycle?: string[]; + exportName?: string; + exporter?: string; + guess?: string; + importer?: string; + missing?: string; + modules?: string[]; + names?: string[]; + reexporter?: string; + source?: string; + sources?: string[]; +} + +interface RollupLogProps { + code?: string; + frame?: string; + hook?: string; + id?: string; + loc?: { + column: number; + file?: string; + line: number; + }; + message: string; + name?: string; + plugin?: string; + pluginCode?: string; + pos?: number; + url?: string; +} + +interface ExistingRawSourceMap { + file?: string; + mappings: string; + names: string[]; + sourceRoot?: string; + sources: string[]; + sourcesContent?: string[]; + version: number; +} + +interface SourceMap { + file: string; + mappings: string; + names: string[]; + sources: string[]; + sourcesContent: string[]; + version: number; + toString(): string; + toUrl(): string; +} + +type SourceMapInput = ExistingRawSourceMap | string | null | { mappings: '' }; + +type PartialNull = { + [P in keyof T]: T[P] | null; +}; + +interface ModuleOptions { + meta: CustomPluginOptions; + moduleSideEffects: boolean | 'no-treeshake'; + syntheticNamedExports: boolean | string; +} + +interface SourceDescription extends Partial> { + ast?: AcornNode; + code: string; + map?: SourceMapInput; +} + +interface PluginCache { + delete(id: string): boolean; + get(id: string): T; + has(id: string): boolean; + set(id: string, value: T): void; +} + +interface MinimalPluginContext { + meta: PluginContextMeta; +} + +interface EmittedAsset { + fileName?: string; + name?: string; + source?: string | Uint8Array; + type: 'asset'; +} + +interface EmittedChunk { + fileName?: string; + id: string; + implicitlyLoadedAfterOneOf?: string[]; + importer?: string; + name?: string; + preserveSignature?: PreserveEntrySignaturesOption; + type: 'chunk'; +} + +type EmittedFile = EmittedAsset | EmittedChunk; + +type EmitAsset = (name: string, source?: string | Uint8Array) => string; + +type EmitChunk = (id: string, options?: { name?: string }) => string; + +type EmitFile = (emittedFile: EmittedFile) => string; + +interface ModuleInfo extends ModuleOptions { + ast: AcornNode | null; + code: string | null; + dynamicImporters: readonly string[]; + dynamicallyImportedIdResolutions: readonly ResolvedId[]; + dynamicallyImportedIds: readonly string[]; + hasDefaultExport: boolean | null; + /** @deprecated Use `moduleSideEffects` instead */ + hasModuleSideEffects: boolean | 'no-treeshake'; + id: string; + implicitlyLoadedAfterOneOf: readonly string[]; + implicitlyLoadedBefore: readonly string[]; + importedIdResolutions: readonly ResolvedId[]; + importedIds: readonly string[]; + importers: readonly string[]; + isEntry: boolean; + isExternal: boolean; + isIncluded: boolean | null; +} + +type GetModuleInfo = (moduleId: string) => ModuleInfo | null; + +interface CustomPluginOptions { + [plugin: string]: any; +} + +interface PluginContext extends MinimalPluginContext { + addWatchFile: (id: string) => void; + cache: PluginCache; + /** @deprecated Use `this.emitFile` instead */ + emitAsset: EmitAsset; + /** @deprecated Use `this.emitFile` instead */ + emitChunk: EmitChunk; + emitFile: EmitFile; + error: (err: RollupError | string, pos?: number | { column: number; line: number }) => never; + /** @deprecated Use `this.getFileName` instead */ + getAssetFileName: (assetReferenceId: string) => string; + /** @deprecated Use `this.getFileName` instead */ + getChunkFileName: (chunkReferenceId: string) => string; + getFileName: (fileReferenceId: string) => string; + getModuleIds: () => IterableIterator; + getModuleInfo: GetModuleInfo; + getWatchFiles: () => string[]; + /** @deprecated Use `this.resolve` instead */ + isExternal: IsExternal; + load: ( + options: { id: string; resolveDependencies?: boolean } & Partial> + ) => Promise; + /** @deprecated Use `this.getModuleIds` instead */ + moduleIds: IterableIterator; + parse: (input: string, options?: any) => AcornNode; + resolve: ( + source: string, + importer?: string, + options?: { custom?: CustomPluginOptions; isEntry?: boolean; skipSelf?: boolean } + ) => Promise; + /** @deprecated Use `this.resolve` instead */ + resolveId: (source: string, importer?: string) => Promise; + setAssetSource: (assetReferenceId: string, source: string | Uint8Array) => void; + warn: (warning: RollupWarning | string, pos?: number | { column: number; line: number }) => void; +} + +interface PluginContextMeta { + rollupVersion: string; + watchMode: boolean; +} + +interface ResolvedId extends ModuleOptions { + external: boolean | 'absolute'; + id: string; +} + +type IsExternal = ( + source: string, + importer: string | undefined, + isResolved: boolean +) => boolean; + +interface TransformPluginContext extends PluginContext { + getCombinedSourcemap: () => SourceMap; +} + +type TransformResult = string | null | void | Partial; +type PreserveEntrySignaturesOption = false | 'strict' | 'allow-extension' | 'exports-only'; + +interface AcornNode { + end: number; + start: number; + type: string; +} + +type Awaitable = T | PromiseLike; +type Nullable = T | null | undefined; +type Arrayable = T | Array; +type ArgumentsType$1 = T extends (...args: infer U) => any ? U : never; +type MergeInsertions = T extends object ? { + [K in keyof T]: MergeInsertions; +} : T; +type DeepMerge = MergeInsertions<{ + [K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never; +}>; +type MutableArray = { + -readonly [k in keyof T]: T[k]; +}; +interface Constructable { + new (...args: any[]): any; +} +interface ModuleCache { + promise?: Promise; + exports?: any; + code?: string; +} +interface EnvironmentReturn { + teardown: (global: any) => Awaitable; +} +interface Environment { + name: string; + setup(global: any, options: Record): Awaitable; +} +interface UserConsoleLog { + content: string; + type: 'stdout' | 'stderr'; + taskId?: string; + time: number; + size: number; +} +interface ParsedStack { + method: string; + file: string; + line: number; + column: number; +} +interface ErrorWithDiff extends Error { + name: string; + nameStr?: string; + stack?: string; + stackStr?: string; + stacks?: ParsedStack[]; + showDiff?: boolean; + actual?: any; + expected?: any; + operator?: string; + type?: string; + frame?: string; +} +interface ModuleGraphData { + graph: Record; + externalized: string[]; + inlined: string[]; +} +type OnServerRestartHandler = (reason?: string) => Promise | void; + +declare type ArgumentsType = T extends (...args: infer A) => any ? A : never; +declare type ReturnType$1 = T extends (...args: any) => infer R ? R : never; +declare type PromisifyFn = ReturnType$1 extends Promise ? T : (...args: ArgumentsType) => Promise>>; +declare type BirpcFn = PromisifyFn & { + /** + * Send event without asking for response + */ + asEvent(...args: ArgumentsType): void; +}; +declare type BirpcReturn = { + [K in keyof RemoteFunctions]: BirpcFn; +}; + +type ChainableFunction = { + (...args: Args): R; +} & { + [x in T]: ChainableFunction; +} & { + fn: (this: Record, ...args: Args) => R; +} & E; + +interface BenchmarkUserOptions { + /** + * Include globs for benchmark test files + * + * @default ['**\/*.{bench,benchmark}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'] + */ + include?: string[]; + /** + * Exclude globs for benchmark test files + * @default ['node_modules', 'dist', '.idea', '.git', '.cache'] + */ + exclude?: string[]; + /** + * Include globs for in-source benchmark test files + * + * @default [] + */ + includeSource?: string[]; + /** + * Custom reporter for output. Can contain one or more built-in report names, reporter instances, + * and/or paths to custom reporters + */ + reporters?: Arrayable; + /** + * Write test results to a file when the `--reporter=json` option is also specified. + * Also definable individually per reporter by using an object instead. + */ + outputFile?: string | (Partial> & Record); +} +interface Benchmark extends TaskBase { + type: 'benchmark'; + suite: Suite; + result?: TaskResult; + fails?: boolean; + task?: Task$1; +} +interface BenchmarkResult extends TaskResult$1 { + name: string; + rank: number; +} +type BenchFunction = (this: Bench) => Promise | void; +type BenchmarkAPI = ChainableFunction<'skip' | 'only' | 'todo', [ + name: string, + fn?: BenchFunction, + options?: Options +], void> & { + skipIf(condition: any): BenchmarkAPI; + runIf(condition: any): BenchmarkAPI; +}; + +type RunMode = 'run' | 'skip' | 'only' | 'todo'; +type TaskState = RunMode | 'pass' | 'fail'; +interface TaskBase { + id: string; + name: string; + mode: RunMode; + concurrent?: boolean; + shuffle?: boolean; + suite?: Suite; + file?: File; + result?: TaskResult; + retry?: number; + logs?: UserConsoleLog[]; + meta?: any; +} +interface TaskResult { + state: TaskState; + duration?: number; + startTime?: number; + heap?: number; + /** + * @deprecated Use "errors" instead + */ + error?: ErrorWithDiff; + errors?: ErrorWithDiff[]; + htmlError?: string; + hooks?: Partial>; + benchmark?: BenchmarkResult; + retryCount?: number; +} +type TaskResultPack = [id: string, result: TaskResult | undefined]; +interface Suite extends TaskBase { + type: 'suite'; + tasks: Task[]; + filepath?: string; + benchmark?: Bench; + projectName?: string; +} +interface File extends Suite { + filepath: string; + collectDuration?: number; + setupDuration?: number; +} +interface Test extends TaskBase { + type: 'test'; + suite: Suite; + result?: TaskResult; + fails?: boolean; + context: TestContext & ExtraContext; + onFailed?: OnTestFailedHandler[]; +} +type Task = Test | Suite | File | Benchmark; +type DoneCallback = (error?: any) => void; +type TestFunction = (context: TestContext & ExtraContext) => Awaitable | void; +type ExtractEachCallbackArgs> = { + 1: [T[0]]; + 2: [T[0], T[1]]; + 3: [T[0], T[1], T[2]]; + 4: [T[0], T[1], T[2], T[3]]; + 5: [T[0], T[1], T[2], T[3], T[4]]; + 6: [T[0], T[1], T[2], T[3], T[4], T[5]]; + 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]]; + 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]]; + 9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]]; + 10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]]; + fallback: Array ? U : any>; +}[T extends Readonly<[any]> ? 1 : T extends Readonly<[any, any]> ? 2 : T extends Readonly<[any, any, any]> ? 3 : T extends Readonly<[any, any, any, any]> ? 4 : T extends Readonly<[any, any, any, any, any]> ? 5 : T extends Readonly<[any, any, any, any, any, any]> ? 6 : T extends Readonly<[any, any, any, any, any, any, any]> ? 7 : T extends Readonly<[any, any, any, any, any, any, any, any]> ? 8 : T extends Readonly<[any, any, any, any, any, any, any, any, any]> ? 9 : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> ? 10 : 'fallback']; +interface SuiteEachFunction { + (cases: ReadonlyArray): (name: string, fn: (...args: T) => Awaitable) => void; + >(cases: ReadonlyArray): (name: string, fn: (...args: ExtractEachCallbackArgs) => Awaitable) => void; + (cases: ReadonlyArray): (name: string, fn: (...args: T[]) => Awaitable) => void; +} +interface TestEachFunction { + (cases: ReadonlyArray): (name: string, fn: (...args: T) => Awaitable, options?: number | TestOptions) => void; + >(cases: ReadonlyArray): (name: string, fn: (...args: ExtractEachCallbackArgs) => Awaitable, options?: number | TestOptions) => void; + (cases: ReadonlyArray): (name: string, fn: (...args: T[]) => Awaitable, options?: number | TestOptions) => void; + (...args: [TemplateStringsArray, ...any]): (name: string, fn: (...args: any[]) => Awaitable, options?: number | TestOptions) => void; +} +type ChainableTestAPI = ChainableFunction<'concurrent' | 'only' | 'skip' | 'todo' | 'fails', [ + name: string, + fn?: TestFunction, + options?: number | TestOptions +], void, { + each: TestEachFunction; + (name: string, fn?: TestFunction, options?: number | TestOptions): void; +}>; +interface TestOptions { + /** + * Test timeout. + */ + timeout?: number; + /** + * Times to retry the test if fails. Useful for making flaky tests more stable. + * When retries is up, the last test error will be thrown. + * + * @default 1 + */ + retry?: number; +} +type TestAPI = ChainableTestAPI & { + each: TestEachFunction; + skipIf(condition: any): ChainableTestAPI; + runIf(condition: any): ChainableTestAPI; +}; +type ChainableSuiteAPI = ChainableFunction<'concurrent' | 'only' | 'skip' | 'todo' | 'shuffle', [ + name: string, + factory?: SuiteFactory, + options?: number | TestOptions +], SuiteCollector, { + each: TestEachFunction; + (name: string, factory?: SuiteFactory): SuiteCollector; +}>; +type SuiteAPI = ChainableSuiteAPI & { + each: SuiteEachFunction; + skipIf(condition: any): ChainableSuiteAPI; + runIf(condition: any): ChainableSuiteAPI; +}; +type HookListener = (...args: T) => Awaitable; +type HookCleanupCallback = (() => Awaitable) | void; +interface SuiteHooks { + beforeAll: HookListener<[Suite | File], HookCleanupCallback>[]; + afterAll: HookListener<[Suite | File]>[]; + beforeEach: HookListener<[TestContext & ExtraContext, Suite], HookCleanupCallback>[]; + afterEach: HookListener<[TestContext & ExtraContext, Suite]>[]; +} +interface SuiteCollector { + readonly name: string; + readonly mode: RunMode; + type: 'collector'; + test: TestAPI; + benchmark: BenchmarkAPI; + tasks: (Suite | Test | Benchmark | SuiteCollector)[]; + collect: (file?: File) => Promise; + clear: () => void; + on: >(name: T, ...fn: SuiteHooks[T]) => void; +} +type SuiteFactory = (test: (name: string, fn: TestFunction) => void) => Awaitable; +interface RuntimeContext { + tasks: (SuiteCollector | Test)[]; + currentSuite: SuiteCollector | null; +} +interface TestContext { + /** + * Metadata of the current test + */ + meta: Readonly; + /** + * A expect instance bound to the test + */ + expect: Vi.ExpectStatic; + /** + * Extract hooks on test failed + */ + onTestFailed: (fn: OnTestFailedHandler) => void; +} +type OnTestFailedHandler = (result: TaskResult) => Awaitable; + +type SnapshotData = Record; +type SnapshotUpdateState = 'all' | 'new' | 'none'; +interface SnapshotStateOptions { + updateSnapshot: SnapshotUpdateState; + expand?: boolean; + snapshotFormat?: OptionsReceived; + resolveSnapshotPath?: (path: string, extension: string) => string; +} +interface SnapshotMatchOptions { + testName: string; + received: unknown; + key?: string; + inlineSnapshot?: string; + isInline: boolean; + error?: Error; +} +interface SnapshotResult { + filepath: string; + added: number; + fileDeleted: boolean; + matched: number; + unchecked: number; + uncheckedKeys: Array; + unmatched: number; + updated: number; +} +interface UncheckedSnapshot { + filePath: string; + keys: Array; +} +interface SnapshotSummary { + added: number; + didUpdate: boolean; + failure: boolean; + filesAdded: number; + filesRemoved: number; + filesRemovedList: Array; + filesUnmatched: number; + filesUpdated: number; + matched: number; + total: number; + unchecked: number; + uncheckedKeysByFile: Array; + unmatched: number; + updated: number; +} + +interface WorkerContext { + workerId: number; + port: MessagePort; + config: ResolvedConfig; + files: string[]; + invalidates?: string[]; +} +type ResolveIdFunction = (id: string, importer?: string) => Promise; +interface AfterSuiteRunMeta { + coverage?: unknown; +} +interface WorkerRPC { + fetch: FetchFunction; + resolveId: ResolveIdFunction; + getSourceMap: (id: string, force?: boolean) => Promise; + onFinished: (files: File[], errors?: unknown[]) => void; + onWorkerExit: (code?: number) => void; + onPathsCollected: (paths: string[]) => void; + onUserConsoleLog: (log: UserConsoleLog) => void; + onUnhandledRejection: (err: unknown) => void; + onCollected: (files: File[]) => void; + onAfterSuiteRun: (meta: AfterSuiteRunMeta) => void; + onTaskUpdate: (pack: TaskResultPack[]) => void; + snapshotSaved: (snapshot: SnapshotResult) => void; + resolveSnapshotPath: (testPath: string) => string; +} +interface WorkerGlobalState { + ctx: WorkerContext; + config: ResolvedConfig; + rpc: BirpcReturn; + current?: Test; + filepath?: string; + moduleCache: ModuleCacheMap; + browserHashMap?: Map; + mockMap: MockMap; +} + +interface CoverageProvider { + name: string; + initialize(ctx: Vitest): Promise | void; + resolveOptions(): ResolvedCoverageOptions; + clean(clean?: boolean): void | Promise; + onBeforeFilesRun?(): void | Promise; + onAfterSuiteRun(meta: AfterSuiteRunMeta): void | Promise; + reportCoverage(): void | Promise; + onFileTransform?(sourceCode: string, id: string, pluginCtx: TransformPluginContext): TransformResult | Promise; +} +interface CoverageProviderModule { + /** + * Factory for creating a new coverage provider + */ + getProvider(): CoverageProvider | Promise; + /** + * Executed on after each run in the worker thread. Possible to return a payload passed to the provider + */ + takeCoverage?(): unknown | Promise; +} +type CoverageReporter = 'clover' | 'cobertura' | 'html-spa' | 'html' | 'json-summary' | 'json' | 'lcov' | 'lcovonly' | 'none' | 'teamcity' | 'text-lcov' | 'text-summary' | 'text'; +type CoverageOptions = BaseCoverageOptions & { + provider?: null | CoverageProviderModule; +} | CoverageC8Options & { + provider?: 'c8'; +} | CoverageIstanbulOptions & { + provider?: 'istanbul'; +}; +type ResolvedCoverageOptions = { + tempDirectory: string; +} & Required; +interface BaseCoverageOptions { + /** + * Enables coverage collection. Can be overriden using `--coverage` CLI option. + * + * @default false + */ + enabled?: boolean; + /** + * List of files included in coverage as glob patterns + * + * @default ['**'] + */ + include?: string[]; + /** + * Extensions for files to be included in coverage + * + * @default ['.js', '.cjs', '.mjs', '.ts', '.tsx', '.jsx', '.vue', '.svelte'] + */ + extension?: string | string[]; + /** + * List of files excluded from coverage as glob patterns + */ + exclude?: string[]; + /** + * Whether to include all files, including the untested ones into report + * + * @default false + */ + all?: boolean; + /** + * Clean coverage results before running tests + * + * @default true + */ + clean?: boolean; + /** + * Clean coverage report on watch rerun + * + * @default true + */ + cleanOnRerun?: boolean; + /** + * Directory to write coverage report to + */ + reportsDirectory?: string; + /** + * Coverage reporters to use. + * See [istanbul documentation](https://istanbul.js.org/docs/advanced/alternative-reporters/) for detailed list of all reporters. + * + * @default ['text', 'html', 'clover', 'json'] + */ + reporter?: Arrayable; + /** + * Do not show files with 100% statement, branch, and function coverage + * + * @default false + */ + skipFull?: boolean; + /** + * Check thresholds per file. + * See `lines`, `functions`, `branches` and `statements` for the actual thresholds. + * + * @default false + */ + perFile?: boolean; + /** + * Threshold for lines + * + * @default undefined + */ + lines?: number; + /** + * Threshold for functions + * + * @default undefined + */ + functions?: number; + /** + * Threshold for branches + * + * @default undefined + */ + branches?: number; + /** + * Threshold for statements + * + * @default undefined + */ + statements?: number; +} +interface CoverageIstanbulOptions extends BaseCoverageOptions { + /** + * Set to array of class method names to ignore for coverage + * + * @default [] + */ + ignoreClassMethods?: string[]; + /** + * Watermarks for statements, lines, branches and functions. + * + * Default value is `[50,80]` for each property. + */ + watermarks?: { + statements?: [number, number]; + functions?: [number, number]; + branches?: [number, number]; + lines?: [number, number]; + }; +} +interface CoverageC8Options extends BaseCoverageOptions { + /** + * Allow files from outside of your cwd. + * + * @default false + */ + allowExternal?: boolean; + /** + * Exclude coverage under `/node_modules/` + * + * @default true + */ + excludeNodeModules?: boolean; + /** + * Specifies the directories that are used when `--all` is enabled. + * + * @default cwd + */ + src?: string[]; + /** + * Shortcut for `--check-coverage --lines 100 --functions 100 --branches 100 --statements 100` + * + * @default false + */ + 100?: boolean; +} + +interface JSDOMOptions { + /** + * The html content for the test. + * + * @default '' + */ + html?: string | Buffer | ArrayBufferLike; + /** + * referrer just affects the value read from document.referrer. + * It defaults to no referrer (which reflects as the empty string). + */ + referrer?: string; + /** + * userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources. + * + * @default `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}` + */ + userAgent?: string; + /** + * url sets the value returned by window.location, document.URL, and document.documentURI, + * and affects things like resolution of relative URLs within the document + * and the same-origin restrictions and referrer used while fetching subresources. + * + * @default 'http://localhost:3000'. + */ + url?: string; + /** + * contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML. + * Values that are not "text/html" or an XML mime type will throw. + * + * @default 'text/html'. + */ + contentType?: string; + /** + * The maximum size in code units for the separate storage areas used by localStorage and sessionStorage. + * Attempts to store data larger than this limit will cause a DOMException to be thrown. By default, it is set + * to 5,000,000 code units per origin, as inspired by the HTML specification. + * + * @default 5_000_000 + */ + storageQuota?: number; + /** + * Enable console? + * + * @default false + */ + console?: boolean; + /** + * jsdom does not have the capability to render visual content, and will act like a headless browser by default. + * It provides hints to web pages through APIs such as document.hidden that their content is not visible. + * + * When the `pretendToBeVisual` option is set to `true`, jsdom will pretend that it is rendering and displaying + * content. + * + * @default true + */ + pretendToBeVisual?: boolean; + /** + * `includeNodeLocations` preserves the location info produced by the HTML parser, + * allowing you to retrieve it with the nodeLocation() method (described below). + * + * It defaults to false to give the best performance, + * and cannot be used with an XML content type since our XML parser does not support location info. + * + * @default false + */ + includeNodeLocations?: boolean | undefined; + /** + * @default 'dangerously' + */ + runScripts?: 'dangerously' | 'outside-only'; + /** + * Enable CookieJar + * + * @default false + */ + cookieJar?: boolean; + resources?: 'usable' | any; +} + +interface Reporter { + onInit?(ctx: Vitest): void; + onPathsCollected?: (paths?: string[]) => Awaitable; + onCollected?: (files?: File[]) => Awaitable; + onFinished?: (files?: File[], errors?: unknown[]) => Awaitable; + onTaskUpdate?: (packs: TaskResultPack[]) => Awaitable; + onTestRemoved?: (trigger?: string) => Awaitable; + onWatcherStart?: (files?: File[], errors?: unknown[]) => Awaitable; + onWatcherRerun?: (files: string[], trigger?: string) => Awaitable; + onServerRestart?: (reason?: string) => Awaitable; + onUserConsoleLog?: (log: UserConsoleLog) => Awaitable; +} + +type BuiltinEnvironment = 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime'; +type VitestEnvironment = BuiltinEnvironment | (string & Record); +type CSSModuleScopeStrategy = 'stable' | 'scoped' | 'non-scoped'; +type SequenceHooks = 'stack' | 'list' | 'parallel'; +type ApiConfig = Pick; + +interface EnvironmentOptions { + /** + * jsdom options. + */ + jsdom?: JSDOMOptions; + [x: string]: unknown; +} +type VitestRunMode = 'test' | 'benchmark' | 'typecheck'; +interface InlineConfig { + /** + * Name of the project. Will be used to display in the reporter. + */ + name?: string; + /** + * Benchmark options. + * + * @default {} + */ + benchmark?: BenchmarkUserOptions; + /** + * Include globs for test files + * + * @default ['**\/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'] + */ + include?: string[]; + /** + * Exclude globs for test files + * @default ['node_modules', 'dist', '.idea', '.git', '.cache'] + */ + exclude?: string[]; + /** + * Include globs for in-source test files + * + * @default [] + */ + includeSource?: string[]; + /** + * Handling for dependencies inlining or externalizing + */ + deps?: { + /** + * Externalize means that Vite will bypass the package to native Node. + * + * Externalized dependencies will not be applied Vite's transformers and resolvers. + * And does not support HMR on reload. + * + * Typically, packages under `node_modules` are externalized. + */ + external?: (string | RegExp)[]; + /** + * Vite will process inlined modules. + * + * This could be helpful to handle packages that ship `.js` in ESM format (that Node can't handle). + * + * If `true`, every dependency will be inlined + */ + inline?: (string | RegExp)[] | true; + /** + * Interpret CJS module's default as named exports + * + * @default true + */ + interopDefault?: boolean; + /** + * When a dependency is a valid ESM package, try to guess the cjs version based on the path. + * This will significantly improve the performance in huge repo, but might potentially + * cause some misalignment if a package have different logic in ESM and CJS mode. + * + * @default false + */ + fallbackCJS?: boolean; + /** + * Use experimental Node loader to resolve imports inside node_modules using Vite resolve algorithm. + * @default false + */ + registerNodeLoader?: boolean; + }; + /** + * Base directory to scan for the test files + * + * @default `config.root` + */ + dir?: string; + /** + * Register apis globally + * + * @default false + */ + globals?: boolean; + /** + * Running environment + * + * Supports 'node', 'jsdom', 'happy-dom', 'edge-runtime' + * + * If used unsupported string, will try to load the package `vitest-environment-${env}` + * + * @default 'node' + */ + environment?: VitestEnvironment; + /** + * Environment options. + */ + environmentOptions?: EnvironmentOptions; + /** + * Update snapshot + * + * @default false + */ + update?: boolean; + /** + * Watch mode + * + * @default true + */ + watch?: boolean; + /** + * Project root + * + * @default process.cwd() + */ + root?: string; + /** + * Custom reporter for output. Can contain one or more built-in report names, reporter instances, + * and/or paths to custom reporters. + */ + reporters?: Arrayable>; + /** + * Truncates lines in the output to the given length. + * @default stdout.columns || 80 + */ + outputTruncateLength?: number; + /** + * Maximum number of line to show in a single diff. + * @default 15 + */ + outputDiffLines?: number; + /** + * The maximum number of characters allowed in a single object before doing a diff. + * Vitest tries to stringify an object before doing a diff, but if the object is too large, + * it will reduce the depth of the object to fit within this limit. + * Because of this if object is too big or nested, you might not see the diff. + * @default 10000 + */ + outputDiffMaxSize?: number; + /** + * Maximum number of lines in a diff overall. + * @default 50 + */ + outputDiffMaxLines?: number; + /** + * Write test results to a file when the --reporter=json` or `--reporter=junit` option is also specified. + * Also definable individually per reporter by using an object instead. + */ + outputFile?: string | (Partial> & Record); + /** + * Enable multi-threading + * + * @default true + */ + threads?: boolean; + /** + * Maximum number of threads + * + * @default available CPUs + */ + maxThreads?: number; + /** + * Minimum number of threads + * + * @default available CPUs + */ + minThreads?: number; + /** + * Default timeout of a test in milliseconds + * + * @default 5000 + */ + testTimeout?: number; + /** + * Default timeout of a hook in milliseconds + * + * @default 10000 + */ + hookTimeout?: number; + /** + * Default timeout to wait for close when Vitest shuts down, in milliseconds + * + * @default 1000 + */ + teardownTimeout?: number; + /** + * Silent mode + * + * @default false + */ + silent?: boolean; + /** + * Path to setup files + */ + setupFiles?: string | string[]; + /** + * Path to global setup files + */ + globalSetup?: string | string[]; + /** + * Glob pattern of file paths to be ignore from triggering watch rerun + */ + watchExclude?: string[]; + /** + * Glob patter of file paths that will trigger the whole suite rerun + * + * Useful if you are testing calling CLI commands + * + * @default [] + */ + forceRerunTriggers?: string[]; + /** + * Isolate environment for each test file + * + * @default true + */ + isolate?: boolean; + /** + * Coverage options + */ + coverage?: CoverageOptions; + /** + * run test names with the specified pattern + */ + testNamePattern?: string | RegExp; + /** + * Will call `.mockClear()` on all spies before each test + * @default false + */ + clearMocks?: boolean; + /** + * Will call `.mockReset()` on all spies before each test + * @default false + */ + mockReset?: boolean; + /** + * Will call `.mockRestore()` on all spies before each test + * @default false + */ + restoreMocks?: boolean; + /** + * Will restore all global stubs to their original values before each test + * @default false + */ + unstubGlobals?: boolean; + /** + * Will restore all env stubs to their original values before each test + * @default false + */ + unstubEnvs?: boolean; + /** + * Serve API options. + * + * When set to true, the default port is 51204. + * + * @default false + */ + api?: boolean | number | ApiConfig; + /** + * Enable Vitest UI + * @internal WIP + */ + ui?: boolean; + /** + * Use in browser environment + * @experimental + */ + browser?: boolean; + /** + * Open UI automatically. + * + * @default true + */ + open?: boolean; + /** + * Base url for the UI + * + * @default '/__vitest__/' + */ + uiBase?: string; + /** + * Determine the transform method of modules + */ + transformMode?: { + /** + * Use SSR transform pipeline for the specified files. + * Vite plugins will receive `ssr: true` flag when processing those files. + * + * @default [/\.([cm]?[jt]sx?|json)$/] + */ + ssr?: RegExp[]; + /** + * First do a normal transform pipeline (targeting browser), + * then then do a SSR rewrite to run the code in Node. + * Vite plugins will receive `ssr: false` flag when processing those files. + * + * @default other than `ssr` + */ + web?: RegExp[]; + }; + /** + * Format options for snapshot testing. + */ + snapshotFormat?: PrettyFormatOptions; + /** + * Resolve custom snapshot path + */ + resolveSnapshotPath?: (path: string, extension: string) => string; + /** + * Pass with no tests + */ + passWithNoTests?: boolean; + /** + * Allow tests and suites that are marked as only + */ + allowOnly?: boolean; + /** + * Show heap usage after each test. Useful for debugging memory leaks. + */ + logHeapUsage?: boolean; + /** + * Custom environment variables assigned to `process.env` before running tests. + */ + env?: Record; + /** + * Options for @sinon/fake-timers + */ + fakeTimers?: FakeTimerInstallOpts; + /** + * Custom handler for console.log in tests. + * + * Return `false` to ignore the log. + */ + onConsoleLog?: (log: string, type: 'stdout' | 'stderr') => false | void; + /** + * Indicates if CSS files should be processed. + * + * When excluded, the CSS files will be replaced with empty strings to bypass the subsequent processing. + * + * @default { include: [], modules: { classNameStrategy: false } } + */ + css?: boolean | { + include?: RegExp | RegExp[]; + exclude?: RegExp | RegExp[]; + modules?: { + classNameStrategy?: CSSModuleScopeStrategy; + }; + }; + /** + * A number of tests that are allowed to run at the same time marked with `test.concurrent`. + * @default 5 + */ + maxConcurrency?: number; + /** + * Options for configuring cache policy. + * @default { dir: 'node_modules/.vitest' } + */ + cache?: false | { + dir?: string; + }; + /** + * Options for configuring the order of running tests. + */ + sequence?: { + /** + * Class that handles sorting and sharding algorithm. + * If you only need to change sorting, you can extend + * your custom sequencer from `BaseSequencer` from `vitest/node`. + * @default BaseSequencer + */ + sequencer?: TestSequencerConstructor; + /** + * Should tests run in random order. + * @default false + */ + shuffle?: boolean; + /** + * Seed for the random number generator. + * @default Date.now() + */ + seed?: number; + /** + * Defines how hooks should be ordered + * - `stack` will order "after" hooks in reverse order, "before" hooks will run sequentially + * - `list` will order hooks in the order they are defined + * - `parallel` will run hooks in a single group in parallel + * @default 'parallel' + */ + hooks?: SequenceHooks; + }; + /** + * Specifies an `Object`, or an `Array` of `Object`, + * which defines aliases used to replace values in `import` or `require` statements. + * Will be merged with the default aliases inside `resolve.alias`. + */ + alias?: AliasOptions; + /** + * Ignore any unhandled errors that occur + */ + dangerouslyIgnoreUnhandledErrors?: boolean; + /** + * Options for configuring typechecking test environment. + */ + typecheck?: Partial; + /** + * The number of milliseconds after which a test is considered slow and reported as such in the results. + * + * @default 300 + */ + slowTestThreshold?: number; +} +interface TypecheckConfig { + /** + * What tools to use for type checking. + */ + checker: 'tsc' | 'vue-tsc' | (string & Record); + /** + * Pattern for files that should be treated as test files + */ + include: string[]; + /** + * Pattern for files that should not be treated as test files + */ + exclude: string[]; + /** + * Check JS files that have `@ts-check` comment. + * If you have it enabled in tsconfig, this will not overwrite it. + */ + allowJs?: boolean; + /** + * Do not fail, if Vitest found errors outside the test files. + */ + ignoreSourceErrors?: boolean; + /** + * Path to tsconfig, relative to the project root. + */ + tsconfig?: string; +} +interface UserConfig extends InlineConfig { + /** + * Path to the config file. + * + * Default resolving to `vitest.config.*`, `vite.config.*` + */ + config?: string | undefined; + /** + * Use happy-dom + */ + dom?: boolean; + /** + * Run tests that cover a list of source files + */ + related?: string[] | string; + /** + * Overrides Vite mode + * @default 'test' + */ + mode?: string; + /** + * Runs tests that are affected by the changes in the repository, or between specified branch or commit hash + * Requires initialized git repository + * @default false + */ + changed?: boolean | string; + /** + * Test suite shard to execute in a format of /. + * Will divide tests into a `count` numbers, and run only the `indexed` part. + * Cannot be used with enabled watch. + * @example --shard=2/3 + */ + shard?: string; +} +interface ResolvedConfig extends Omit, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'related' | 'api' | 'reporters' | 'resolveSnapshotPath' | 'benchmark' | 'shard' | 'cache' | 'sequence' | 'typecheck'> { + mode: VitestRunMode; + base?: string; + config?: string; + filters?: string[]; + testNamePattern?: RegExp; + related?: string[]; + coverage: ResolvedCoverageOptions; + snapshotOptions: SnapshotStateOptions; + reporters: (Reporter | BuiltinReporters)[]; + defines: Record; + api?: ApiConfig; + benchmark?: Required> & { + outputFile?: BenchmarkUserOptions['outputFile']; + }; + shard?: { + index: number; + count: number; + }; + cache: { + dir: string; + } | false; + sequence: { + sequencer: TestSequencerConstructor; + hooks: SequenceHooks; + shuffle?: boolean; + seed?: number; + }; + typecheck: TypecheckConfig; +} +type RuntimeConfig = Pick & { + sequence?: { + hooks?: SequenceHooks; + }; +}; + +type VitestInlineConfig = InlineConfig; +declare module 'vite' { + interface UserConfig { + /** + * Options for Vitest + */ + test?: VitestInlineConfig; + } +} + +declare function stringify(object: unknown, maxDepth?: number, { maxLength, ...options }?: PrettyFormatOptions & { + maxLength?: number; +}): string; + +type Formatter = (input: string | number | null | undefined) => string; + +declare const EXPECTED_COLOR: Formatter; +declare const RECEIVED_COLOR: Formatter; +declare const INVERTED_COLOR: Formatter; +declare const BOLD_WEIGHT: Formatter; +declare const DIM_COLOR: Formatter; +declare function matcherHint(matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions): string; +declare const printReceived: (object: unknown) => string; +declare const printExpected: (value: unknown) => string; +declare function diff(a: any, b: any, options?: DiffOptions): string; + +declare const jestMatcherUtils_stringify: typeof stringify; +declare const jestMatcherUtils_EXPECTED_COLOR: typeof EXPECTED_COLOR; +declare const jestMatcherUtils_RECEIVED_COLOR: typeof RECEIVED_COLOR; +declare const jestMatcherUtils_INVERTED_COLOR: typeof INVERTED_COLOR; +declare const jestMatcherUtils_BOLD_WEIGHT: typeof BOLD_WEIGHT; +declare const jestMatcherUtils_DIM_COLOR: typeof DIM_COLOR; +declare const jestMatcherUtils_matcherHint: typeof matcherHint; +declare const jestMatcherUtils_printReceived: typeof printReceived; +declare const jestMatcherUtils_printExpected: typeof printExpected; +declare const jestMatcherUtils_diff: typeof diff; +declare namespace jestMatcherUtils { + export { + jestMatcherUtils_stringify as stringify, + jestMatcherUtils_EXPECTED_COLOR as EXPECTED_COLOR, + jestMatcherUtils_RECEIVED_COLOR as RECEIVED_COLOR, + jestMatcherUtils_INVERTED_COLOR as INVERTED_COLOR, + jestMatcherUtils_BOLD_WEIGHT as BOLD_WEIGHT, + jestMatcherUtils_DIM_COLOR as DIM_COLOR, + jestMatcherUtils_matcherHint as matcherHint, + jestMatcherUtils_printReceived as printReceived, + jestMatcherUtils_printExpected as printExpected, + jestMatcherUtils_diff as diff, + }; +} +type Tester = (a: any, b: any) => boolean | undefined; +interface MatcherHintOptions { + comment?: string; + expectedColor?: Formatter; + isDirectExpectCall?: boolean; + isNot?: boolean; + promise?: string; + receivedColor?: Formatter; + secondArgument?: string; + secondArgumentColor?: Formatter; +} +interface DiffOptions { + aAnnotation?: string; + aColor?: Formatter; + aIndicator?: string; + bAnnotation?: string; + bColor?: Formatter; + bIndicator?: string; + changeColor?: Formatter; + changeLineTrailingSpaceColor?: Formatter; + commonColor?: Formatter; + commonIndicator?: string; + commonLineTrailingSpaceColor?: Formatter; + contextLines?: number; + emptyFirstOrLastLinePlaceholder?: string; + expand?: boolean; + includeChangeCounts?: boolean; + omitAnnotationLines?: boolean; + patchColor?: Formatter; + compareKeys?: any; +} +interface MatcherState$1 { + assertionCalls: number; + currentTestName?: string; + dontThrow?: () => void; + error?: Error; + equals: (a: unknown, b: unknown, customTesters?: Array, strictCheck?: boolean) => boolean; + expand?: boolean; + expectedAssertionsNumber?: number | null; + expectedAssertionsNumberErrorGen?: (() => Error) | null; + isExpectingAssertions?: boolean; + isExpectingAssertionsError?: Error | null; + isNot: boolean; + promise: string; + suppressedErrors: Array; + testPath?: string; + utils: typeof jestMatcherUtils & { + iterableEquality: Tester; + subsetEquality: Tester; + }; +} +interface SyncExpectationResult { + pass: boolean; + message: () => string; + actual?: any; + expected?: any; +} +type AsyncExpectationResult = Promise; +type ExpectationResult = SyncExpectationResult | AsyncExpectationResult; +interface RawMatcherFn { + (this: T, received: any, expected: any, options?: any): ExpectationResult; +} +type MatchersObject = Record>; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +interface SnapshotReturnOptions { + actual: string; + count: number; + expected?: string; + key: string; + pass: boolean; +} +interface SaveStatus { + deleted: boolean; + saved: boolean; +} +declare class SnapshotState { + testFilePath: string; + snapshotPath: string; + private _counters; + private _dirty; + private _updateSnapshot; + private _snapshotData; + private _initialData; + private _inlineSnapshots; + private _uncheckedKeys; + private _snapshotFormat; + added: number; + expand: boolean; + matched: number; + unmatched: number; + updated: number; + constructor(testFilePath: string, snapshotPath: string, options: SnapshotStateOptions); + markSnapshotsAsCheckedForTest(testName: string): void; + private _inferInlineSnapshotStack; + private _addSnapshot; + clear(): void; + save(): Promise; + getUncheckedCount(): number; + getUncheckedKeys(): Array; + removeUncheckedKeys(): void; + match({ testName, received, key, inlineSnapshot, isInline, error, }: SnapshotMatchOptions): SnapshotReturnOptions; + pack(): Promise; +} + +interface MatcherState extends MatcherState$1 { + environment: VitestEnvironment; + snapshotState: SnapshotState; +} + +type Promisify = { + [K in keyof O]: O[K] extends (...args: infer A) => infer R ? O extends R ? Promisify : (...args: A) => Promise : O[K]; +}; +declare global { + namespace jest { + interface Matchers { + } + } + namespace Vi { + interface ExpectStatic extends Chai.ExpectStatic, AsymmetricMatchersContaining { + (actual: T, message?: string): Vi.Assertion; + extend(expects: MatchersObject): void; + assertions(expected: number): void; + hasAssertions(): void; + anything(): any; + any(constructor: unknown): any; + addSnapshotSerializer(plugin: Plugin): void; + getState(): MatcherState; + setState(state: Partial): void; + not: AsymmetricMatchersContaining; + } + interface AsymmetricMatchersContaining { + stringContaining(expected: string): any; + objectContaining(expected: any): any; + arrayContaining(expected: Array): any; + stringMatching(expected: string | RegExp): any; + } + interface JestAssertion extends jest.Matchers { + toMatchSnapshot(snapshot: Partial, message?: string): void; + toMatchSnapshot(message?: string): void; + matchSnapshot(snapshot: Partial, message?: string): void; + matchSnapshot(message?: string): void; + toMatchInlineSnapshot(properties: Partial, snapshot?: string, message?: string): void; + toMatchInlineSnapshot(snapshot?: string, message?: string): void; + toThrowErrorMatchingSnapshot(message?: string): void; + toThrowErrorMatchingInlineSnapshot(snapshot?: string, message?: string): void; + toEqual(expected: E): void; + toStrictEqual(expected: E): void; + toBe(expected: E): void; + toMatch(expected: string | RegExp): void; + toMatchObject(expected: E): void; + toContain(item: E): void; + toContainEqual(item: E): void; + toBeTruthy(): void; + toBeFalsy(): void; + toBeGreaterThan(num: number | bigint): void; + toBeGreaterThanOrEqual(num: number | bigint): void; + toBeLessThan(num: number | bigint): void; + toBeLessThanOrEqual(num: number | bigint): void; + toBeNaN(): void; + toBeUndefined(): void; + toBeNull(): void; + toBeDefined(): void; + toBeTypeOf(expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined'): void; + toBeInstanceOf(expected: E): void; + toBeCalledTimes(times: number): void; + toHaveLength(length: number): void; + toHaveProperty(property: string | string[], value?: E): void; + toBeCloseTo(number: number, numDigits?: number): void; + toHaveBeenCalledTimes(times: number): void; + toHaveBeenCalledOnce(): void; + toHaveBeenCalled(): void; + toBeCalled(): void; + toHaveBeenCalledWith(...args: E): void; + toBeCalledWith(...args: E): void; + toHaveBeenNthCalledWith(n: number, ...args: E): void; + nthCalledWith(nthCall: number, ...args: E): void; + toHaveBeenLastCalledWith(...args: E): void; + lastCalledWith(...args: E): void; + toThrow(expected?: string | Constructable | RegExp | Error): void; + toThrowError(expected?: string | Constructable | RegExp | Error): void; + toReturn(): void; + toHaveReturned(): void; + toReturnTimes(times: number): void; + toHaveReturnedTimes(times: number): void; + toReturnWith(value: E): void; + toHaveReturnedWith(value: E): void; + toHaveLastReturnedWith(value: E): void; + lastReturnedWith(value: E): void; + toHaveNthReturnedWith(nthCall: number, value: E): void; + nthReturnedWith(nthCall: number, value: E): void; + toSatisfy(matcher: (value: E) => boolean, message?: string): void; + } + type VitestAssertion = { + [K in keyof A]: A[K] extends Chai.Assertion ? Assertion : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion; + } & ((type: string, message?: string) => Assertion); + interface Assertion extends VitestAssertion, JestAssertion { + resolves: Promisify>; + rejects: Promisify>; + } + } +} + +type RawErrsMap = Map; +interface TscErrorInfo { + filePath: string; + errCode: number; + errMsg: string; + line: number; + column: number; +} +interface CollectLineNumbers { + target: number; + next: number; + prev?: number; +} +type CollectLines = { + [key in keyof CollectLineNumbers]: string; +}; +interface RootAndTarget { + root: string; + targetAbsPath: string; +} +type Context = RootAndTarget & { + rawErrsMap: RawErrsMap; + openedDirs: Set; + lastActivePath?: string; +}; + +export { WorkerContext as $, ApiConfig as A, BuiltinEnvironment as B, CollectLineNumbers as C, DoneCallback as D, EnvironmentOptions as E, FakeTimerInstallOpts as F, SuiteFactory as G, HookListener as H, InlineConfig as I, JSDOMOptions as J, RuntimeContext as K, TestContext as L, MockFactoryWithHelper as M, Vitest as N, OnTestFailedHandler as O, SnapshotData as P, SnapshotUpdateState as Q, RuntimeConfig as R, SequenceHooks as S, TaskResultPack as T, UserConfig as U, VitestEnvironment as V, SnapshotStateOptions as W, SnapshotMatchOptions as X, SnapshotResult as Y, UncheckedSnapshot as Z, SnapshotSummary as _, File as a, ResolveIdFunction as a0, AfterSuiteRunMeta as a1, WorkerRPC as a2, WorkerGlobalState as a3, Awaitable as a4, Nullable as a5, Arrayable as a6, ArgumentsType$1 as a7, MergeInsertions as a8, DeepMerge as a9, TestSequencerConstructor as aA, MutableArray as aa, Constructable as ab, ModuleCache as ac, EnvironmentReturn as ad, Environment as ae, UserConsoleLog as af, ParsedStack as ag, ErrorWithDiff as ah, OnServerRestartHandler as ai, CoverageProvider as aj, CoverageProviderModule as ak, CoverageReporter as al, CoverageOptions as am, ResolvedCoverageOptions as an, BaseCoverageOptions as ao, CoverageIstanbulOptions as ap, CoverageC8Options as aq, BenchmarkUserOptions as ar, Benchmark as as, BenchmarkResult as at, BenchFunction as au, BenchmarkAPI as av, MockFactory as aw, MockMap as ax, TestSequencer as ay, startVitest as az, ResolvedConfig as b, ModuleGraphData as c, Reporter as d, RawErrsMap as e, TscErrorInfo as f, CollectLines as g, RootAndTarget as h, Context as i, CSSModuleScopeStrategy as j, VitestRunMode as k, TypecheckConfig as l, RunMode as m, TaskState as n, TaskBase as o, TaskResult as p, Suite as q, Test as r, Task as s, TestFunction as t, TestOptions as u, TestAPI as v, SuiteAPI as w, HookCleanupCallback as x, SuiteHooks as y, SuiteCollector as z }; diff --git a/node_modules/vitest/dist/vendor-_commonjsHelpers.addc3445.js b/node_modules/vitest/dist/vendor-_commonjsHelpers.addc3445.js new file mode 100644 index 0000000..f116612 --- /dev/null +++ b/node_modules/vitest/dist/vendor-_commonjsHelpers.addc3445.js @@ -0,0 +1,3 @@ +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +export { commonjsGlobal as c }; diff --git a/node_modules/vitest/dist/vendor-index.2e96c50b.js b/node_modules/vitest/dist/vendor-index.2e96c50b.js new file mode 100644 index 0000000..904859d --- /dev/null +++ b/node_modules/vitest/dist/vendor-index.2e96c50b.js @@ -0,0 +1,215 @@ +import 'acorn'; +import { builtinModules } from 'node:module'; +import 'node:fs'; +import { pathToFileURL } from 'node:url'; +import 'url'; +import 'fs'; +import 'path'; +import 'module'; +import assert from 'assert'; +import { format, inspect } from 'util'; +import 'node:path'; + +const BUILTIN_MODULES = new Set(builtinModules); + +const isWindows = process.platform === "win32"; +const own$1 = {}.hasOwnProperty; +const messages = /* @__PURE__ */ new Map(); +const nodeInternalPrefix = "__node_internal_"; +let userStackTraceLimit; +createError( + "ERR_INVALID_MODULE_SPECIFIER", + (request, reason, base = void 0) => { + return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`; + }, + TypeError +); +createError( + "ERR_INVALID_PACKAGE_CONFIG", + (path, base, message) => { + return `Invalid package config ${path}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`; + }, + Error +); +createError( + "ERR_INVALID_PACKAGE_TARGET", + (pkgPath, key, target, isImport = false, base = void 0) => { + const relError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./"); + if (key === ".") { + assert(isImport === false); + return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ""}${relError ? '; targets must start with "./"' : ""}`; + } + return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify( + target + )} defined for '${key}' in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ""}${relError ? '; targets must start with "./"' : ""}`; + }, + Error +); +createError( + "ERR_MODULE_NOT_FOUND", + (path, base, type = "package") => { + return `Cannot find ${type} '${path}' imported from ${base}`; + }, + Error +); +createError( + "ERR_PACKAGE_IMPORT_NOT_DEFINED", + (specifier, packagePath, base) => { + return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`; + }, + TypeError +); +createError( + "ERR_PACKAGE_PATH_NOT_EXPORTED", + (pkgPath, subpath, base = void 0) => { + if (subpath === ".") { + return `No "exports" main defined in ${pkgPath}package.json${base ? ` imported from ${base}` : ""}`; + } + return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${base ? ` imported from ${base}` : ""}`; + }, + Error +); +createError( + "ERR_UNSUPPORTED_DIR_IMPORT", + "Directory import '%s' is not supported resolving ES modules imported from %s", + Error +); +createError( + "ERR_UNKNOWN_FILE_EXTENSION", + 'Unknown file extension "%s" for %s', + TypeError +); +createError( + "ERR_INVALID_ARG_VALUE", + (name, value, reason = "is invalid") => { + let inspected = inspect(value); + if (inspected.length > 128) { + inspected = `${inspected.slice(0, 128)}...`; + } + const type = name.includes(".") ? "property" : "argument"; + return `The ${type} '${name}' ${reason}. Received ${inspected}`; + }, + TypeError +); +createError( + "ERR_UNSUPPORTED_ESM_URL_SCHEME", + (url) => { + let message = "Only file and data URLs are supported by the default ESM loader"; + if (isWindows && url.protocol.length === 2) { + message += ". On Windows, absolute paths must be valid file:// URLs"; + } + message += `. Received protocol '${url.protocol}'`; + return message; + }, + Error +); +function createError(sym, value, def) { + messages.set(sym, value); + return makeNodeErrorWithCode(def, sym); +} +function makeNodeErrorWithCode(Base, key) { + return NodeError; + function NodeError(...args) { + const limit = Error.stackTraceLimit; + if (isErrorStackTraceLimitWritable()) { + Error.stackTraceLimit = 0; + } + const error = new Base(); + if (isErrorStackTraceLimitWritable()) { + Error.stackTraceLimit = limit; + } + const message = getMessage(key, args, error); + Object.defineProperty(error, "message", { + value: message, + enumerable: false, + writable: true, + configurable: true + }); + Object.defineProperty(error, "toString", { + value() { + return `${this.name} [${key}]: ${this.message}`; + }, + enumerable: false, + writable: true, + configurable: true + }); + addCodeToName(error, Base.name, key); + error.code = key; + return error; + } +} +const addCodeToName = hideStackFrames( + function(error, name, code) { + error = captureLargerStackTrace(error); + error.name = `${name} [${code}]`; + error.stack; + if (name === "SystemError") { + Object.defineProperty(error, "name", { + value: name, + enumerable: false, + writable: true, + configurable: true + }); + } else { + delete error.name; + } + } +); +function isErrorStackTraceLimitWritable() { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) { + return Object.isExtensible(Error); + } + return own$1.call(desc, "writable") ? desc.writable : desc.set !== void 0; +} +function hideStackFrames(fn) { + const hidden = nodeInternalPrefix + fn.name; + Object.defineProperty(fn, "name", { value: hidden }); + return fn; +} +const captureLargerStackTrace = hideStackFrames( + function(error) { + const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); + if (stackTraceLimitIsWritable) { + userStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Number.POSITIVE_INFINITY; + } + Error.captureStackTrace(error); + if (stackTraceLimitIsWritable) { + Error.stackTraceLimit = userStackTraceLimit; + } + return error; + } +); +function getMessage(key, args, self) { + const message = messages.get(key); + if (typeof message === "function") { + assert( + message.length <= args.length, + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${message.length}).` + ); + return Reflect.apply(message, self, args); + } + const expectedLength = (message.match(/%[dfijoOs]/g) || []).length; + assert( + expectedLength === args.length, + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` + ); + if (args.length === 0) { + return message; + } + args.unshift(message); + return Reflect.apply(format, null, args); +} +Object.freeze(["node", "import"]); +function isNodeBuiltin(id = "") { + id = id.replace(/^node:/, "").split("/")[0]; + return BUILTIN_MODULES.has(id); +} +pathToFileURL(process.cwd()); +const CJS_RE = /([\s;]|^)(module.exports\b|exports\.\w|require\s*\(|global\.\w)/m; +function hasCJSSyntax(code) { + return CJS_RE.test(code); +} + +export { hasCJSSyntax as h, isNodeBuiltin as i }; diff --git a/node_modules/vitest/dist/vendor-index.534e612c.js b/node_modules/vitest/dist/vendor-index.534e612c.js new file mode 100644 index 0000000..4bca45e --- /dev/null +++ b/node_modules/vitest/dist/vendor-index.534e612c.js @@ -0,0 +1,147 @@ +import { c as commonjsGlobal } from './vendor-_commonjsHelpers.addc3445.js'; + +function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); +} + +var eventTargetPolyfill = {}; + +const root = + (typeof globalThis !== "undefined" && globalThis) || + (typeof self !== "undefined" && self) || + (typeof commonjsGlobal !== "undefined" && commonjsGlobal); + +function isConstructor(fn) { + try { + new fn(); + } catch (error) { + return false; + } + return true; +} + +if (typeof root.Event !== "function" || !isConstructor(root.Event)) { + root.Event = (function () { + function Event(type, options) { + this.bubbles = !!options && !!options.bubbles; + this.cancelable = !!options && !!options.cancelable; + this.composed = !!options && !!options.composed; + this.type = type; + } + + return Event; + })(); +} + +if (typeof root.EventTarget === "undefined" || !isConstructor(root.Event)) { + root.EventTarget = (function () { + function EventTarget() { + this.__listeners = new Map(); + } + + EventTarget.prototype = Object.create(Object.prototype); + + EventTarget.prototype.addEventListener = function ( + type, + listener, + options + ) { + if (arguments.length < 2) { + throw new TypeError( + `TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only ${arguments.length} present.` + ); + } + const __listeners = this.__listeners; + const actualType = type.toString(); + if (!__listeners.has(actualType)) { + __listeners.set(actualType, new Map()); + } + const listenersForType = __listeners.get(actualType); + if (!listenersForType.has(listener)) { + // Any given listener is only registered once + listenersForType.set(listener, options); + } + }; + + EventTarget.prototype.removeEventListener = function ( + type, + listener, + _options + ) { + if (arguments.length < 2) { + throw new TypeError( + `TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only ${arguments.length} present.` + ); + } + const __listeners = this.__listeners; + const actualType = type.toString(); + if (__listeners.has(actualType)) { + const listenersForType = __listeners.get(actualType); + if (listenersForType.has(listener)) { + listenersForType.delete(listener); + } + } + }; + + EventTarget.prototype.dispatchEvent = function (event) { + if (!(event instanceof Event)) { + throw new TypeError( + `Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.` + ); + } + const type = event.type; + const __listeners = this.__listeners; + const listenersForType = __listeners.get(type); + if (listenersForType) { + for (const [listener, options] of listenersForType.entries()) { + try { + if (typeof listener === "function") { + // Listener functions must be executed with the EventTarget as the `this` context. + listener.call(this, event); + } else if (listener && typeof listener.handleEvent === "function") { + // Listener objects have their handleEvent method called, if they have one + listener.handleEvent(event); + } + } catch (err) { + // We need to report the error to the global error handling event, + // but we do not want to break the loop that is executing the events. + // Unfortunately, this is the best we can do, which isn't great, because the + // native EventTarget will actually do this synchronously before moving to the next + // event in the loop. + setTimeout(() => { + throw err; + }); + } + if (options && options.once) { + // If this was registered with { once: true }, we need + // to remove it now. + listenersForType.delete(listener); + } + } + } + // Since there are no cancellable events on a base EventTarget, + // this should always return true. + return true; + }; + + return EventTarget; + })(); +} + +var index = /*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': eventTargetPolyfill +}, [eventTargetPolyfill]); + +export { index as i }; diff --git a/node_modules/vitest/dist/vendor-index.723a074f.js b/node_modules/vitest/dist/vendor-index.723a074f.js new file mode 100644 index 0000000..3d5cca9 --- /dev/null +++ b/node_modules/vitest/dist/vendor-index.723a074f.js @@ -0,0 +1,102 @@ +import * as tinyspy from 'tinyspy'; + +const spies = /* @__PURE__ */ new Set(); +function isMockFunction(fn2) { + return typeof fn2 === "function" && "_isMockFunction" in fn2 && fn2._isMockFunction; +} +function spyOn(obj, method, accessType) { + const dictionary = { + get: "getter", + set: "setter" + }; + const objMethod = accessType ? { [dictionary[accessType]]: method } : method; + const stub = tinyspy.spyOn(obj, objMethod); + return enhanceSpy(stub); +} +let callOrder = 0; +function enhanceSpy(spy) { + const stub = spy; + let implementation; + let instances = []; + let invocations = []; + const mockContext = { + get calls() { + return stub.calls; + }, + get instances() { + return instances; + }, + get invocationCallOrder() { + return invocations; + }, + get results() { + return stub.results.map(([callType, value]) => { + const type = callType === "error" ? "throw" : "return"; + return { type, value }; + }); + }, + get lastCall() { + return stub.calls[stub.calls.length - 1]; + } + }; + let onceImplementations = []; + let name = stub.name; + stub.getMockName = () => name || "vi.fn()"; + stub.mockName = (n) => { + name = n; + return stub; + }; + stub.mockClear = () => { + stub.reset(); + instances = []; + invocations = []; + return stub; + }; + stub.mockReset = () => { + stub.mockClear(); + implementation = () => void 0; + onceImplementations = []; + return stub; + }; + stub.mockRestore = () => { + stub.mockReset(); + implementation = void 0; + return stub; + }; + stub.getMockImplementation = () => implementation; + stub.mockImplementation = (fn2) => { + implementation = fn2; + return stub; + }; + stub.mockImplementationOnce = (fn2) => { + onceImplementations.push(fn2); + return stub; + }; + stub.mockReturnThis = () => stub.mockImplementation(function() { + return this; + }); + stub.mockReturnValue = (val) => stub.mockImplementation(() => val); + stub.mockReturnValueOnce = (val) => stub.mockImplementationOnce(() => val); + stub.mockResolvedValue = (val) => stub.mockImplementation(() => Promise.resolve(val)); + stub.mockResolvedValueOnce = (val) => stub.mockImplementationOnce(() => Promise.resolve(val)); + stub.mockRejectedValue = (val) => stub.mockImplementation(() => Promise.reject(val)); + stub.mockRejectedValueOnce = (val) => stub.mockImplementationOnce(() => Promise.reject(val)); + Object.defineProperty(stub, "mock", { + get: () => mockContext + }); + stub.willCall(function(...args) { + instances.push(this); + invocations.push(++callOrder); + const impl = onceImplementations.shift() || implementation || stub.getOriginal() || (() => { + }); + return impl.apply(this, args); + }); + spies.add(stub); + return stub; +} +function fn(implementation) { + return enhanceSpy(tinyspy.spyOn({ fn: implementation || (() => { + }) }, "fn")); +} + +export { spies as a, fn as f, isMockFunction as i, spyOn as s }; diff --git a/node_modules/vitest/dist/vendor-index.783e7f3e.js b/node_modules/vitest/dist/vendor-index.783e7f3e.js new file mode 100644 index 0000000..554847a --- /dev/null +++ b/node_modules/vitest/dist/vendor-index.783e7f3e.js @@ -0,0 +1,71 @@ +const DEFAULT_TIMEOUT = 6e4; +function createBirpc(functions, options) { + const { + post, + on, + eventNames = [], + serialize = (i) => i, + deserialize = (i) => i, + timeout = DEFAULT_TIMEOUT + } = options; + const rpcPromiseMap = /* @__PURE__ */ new Map(); + const rpc = new Proxy({}, { + get(_, method) { + const sendEvent = (...args) => { + post(serialize({ m: method, a: args, t: "q" })); + }; + if (eventNames.includes(method)) { + sendEvent.asEvent = sendEvent; + return sendEvent; + } + const sendCall = (...args) => { + return new Promise((resolve, reject) => { + const id = nanoid(); + rpcPromiseMap.set(id, { resolve, reject }); + post(serialize({ m: method, a: args, i: id, t: "q" })); + if (timeout >= 0) { + setTimeout(() => { + reject(new Error(`[birpc] timeout on calling "${method}"`)); + rpcPromiseMap.delete(id); + }, timeout); + } + }); + }; + sendCall.asEvent = sendEvent; + return sendCall; + } + }); + on(async (data, ...extra) => { + const msg = deserialize(data); + if (msg.t === "q") { + const { m: method, a: args } = msg; + let result, error; + try { + result = await functions[method].apply(rpc, args); + } catch (e) { + error = e; + } + if (msg.i) + post(serialize({ t: "s", i: msg.i, r: result, e: error }), ...extra); + } else { + const { i: ack, r: result, e: error } = msg; + const promise = rpcPromiseMap.get(ack); + if (error) + promise?.reject(error); + else + promise?.resolve(result); + rpcPromiseMap.delete(ack); + } + }); + return rpc; +} +const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"; +function nanoid(size = 21) { + let id = ""; + let i = size; + while (i--) + id += urlAlphabet[Math.random() * 64 | 0]; + return id; +} + +export { createBirpc as c }; diff --git a/node_modules/vitest/dist/vendor-index.7a2cebfe.js b/node_modules/vitest/dist/vendor-index.7a2cebfe.js new file mode 100644 index 0000000..0576b2d --- /dev/null +++ b/node_modules/vitest/dist/vendor-index.7a2cebfe.js @@ -0,0 +1,1065 @@ +import require$$0$1 from 'child_process'; +import g from 'path'; +import { c as commonjsGlobal } from './vendor-_commonjsHelpers.addc3445.js'; +import require$$0 from 'fs'; +import assert$1 from 'assert'; +import require$$2 from 'events'; +import require$$0$3 from 'buffer'; +import require$$0$2 from 'stream'; +import util from 'util'; + +var crossSpawn = {exports: {}}; + +var windows; +var hasRequiredWindows; + +function requireWindows () { + if (hasRequiredWindows) return windows; + hasRequiredWindows = 1; + windows = isexe; + isexe.sync = sync; + + var fs = require$$0; + + function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT; + + if (!pathext) { + return true + } + + pathext = pathext.split(';'); + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase(); + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false + } + + function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) + } + + function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)); + }); + } + + function sync (path, options) { + return checkStat(fs.statSync(path), path, options) + } + return windows; +} + +var mode; +var hasRequiredMode; + +function requireMode () { + if (hasRequiredMode) return mode; + hasRequiredMode = 1; + mode = isexe; + isexe.sync = sync; + + var fs = require$$0; + + function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)); + }); + } + + function sync (path, options) { + return checkStat(fs.statSync(path), options) + } + + function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) + } + + function checkMode (stat, options) { + var mod = stat.mode; + var uid = stat.uid; + var gid = stat.gid; + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid(); + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid(); + + var u = parseInt('100', 8); + var g = parseInt('010', 8); + var o = parseInt('001', 8); + var ug = u | g; + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0; + + return ret + } + return mode; +} + +var core; +if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { + core = requireWindows(); +} else { + core = requireMode(); +} + +var isexe_1 = isexe$1; +isexe$1.sync = sync; + +function isexe$1 (path, options, cb) { + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe$1(path, options || {}, function (er, is) { + if (er) { + reject(er); + } else { + resolve(is); + } + }); + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null; + is = false; + } + } + cb(er, is); + }); +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} + +const isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys'; + +const path$2 = g; +const COLON = isWindows ? ';' : ':'; +const isexe = isexe_1; + +const getNotFoundError = (cmd) => + Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); + +const getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON; + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] + : ( + [ + // windows always checks the cwd first + ...(isWindows ? [process.cwd()] : []), + ...(opt.path || process.env.PATH || + /* istanbul ignore next: very unusual */ '').split(colon), + ] + ); + const pathExtExe = isWindows + ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' + : ''; + const pathExt = isWindows ? pathExtExe.split(colon) : ['']; + + if (isWindows) { + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift(''); + } + + return { + pathEnv, + pathExt, + pathExtExe, + } +}; + +const which$1 = (cmd, opt, cb) => { + if (typeof opt === 'function') { + cb = opt; + opt = {}; + } + if (!opt) + opt = {}; + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + + const step = i => new Promise((resolve, reject) => { + if (i === pathEnv.length) + return opt.all && found.length ? resolve(found) + : reject(getNotFoundError(cmd)) + + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + + const pCmd = path$2.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd; + + resolve(subStep(p, i, 0)); + }); + + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i + 1)) + const ext = pathExt[ii]; + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext); + else + return resolve(p + ext) + } + return resolve(subStep(p, i, ii + 1)) + }); + }); + + return cb ? step(0).then(res => cb(null, res), cb) : step(0) +}; + +const whichSync = (cmd, opt) => { + opt = opt || {}; + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + + for (let i = 0; i < pathEnv.length; i ++) { + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + + const pCmd = path$2.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd; + + for (let j = 0; j < pathExt.length; j ++) { + const cur = p + pathExt[j]; + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }); + if (is) { + if (opt.all) + found.push(cur); + else + return cur + } + } catch (ex) {} + } + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) +}; + +var which_1 = which$1; +which$1.sync = whichSync; + +var pathKey$1 = {exports: {}}; + +const pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +pathKey$1.exports = pathKey; +// TODO: Remove this for the next major release +pathKey$1.exports.default = pathKey; + +const path$1 = g; +const which = which_1; +const getPathKey = pathKey$1.exports; + +function resolveCommandAttempt(parsed, withoutPathExt) { + const env = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + // Worker threads do not have process.chdir() + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: env[getPathKey({ env })], + pathExt: withoutPathExt ? path$1.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + if (shouldSwitchCwd) { + process.chdir(cwd); + } + } + + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } + + return resolved; +} + +function resolveCommand$1(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} + +var resolveCommand_1 = resolveCommand$1; + +var _escape = {}; + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; +} + +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; + + // Algorithm below is based on https://qntm.org/cmd + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); + + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } + + return arg; +} + +_escape.command = escapeCommand; +_escape.argument = escapeArgument; + +var shebangRegex$1 = /^#!(.*)/; + +const shebangRegex = shebangRegex$1; + +var shebangCommand$1 = (string = '') => { + const match = string.match(shebangRegex); + + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; +}; + +const fs = require$$0; +const shebangCommand = shebangCommand$1; + +function readShebang$1(command) { + // Read the first 150 bytes from the file + const size = 150; + const buffer = Buffer.alloc(size); + + let fd; + + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } + + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} + +var readShebang_1 = readShebang$1; + +const path = g; +const resolveCommand = resolveCommand_1; +const escape = _escape; +const readShebang = readShebang_1; + +const isWin$2 = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; +} + +function parseNonShell(parsed) { + if (!isWin$2) { + return parsed; + } + + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); + + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); + + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); + + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } + + return parsed; +} + +function parse$1(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; + + // Delegate further parsing to shell or non-shell + return options.shell ? parsed : parseNonShell(parsed); +} + +var parse_1 = parse$1; + +const isWin$1 = process.platform === 'win32'; + +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); +} + +function hookChildProcess(cp, parsed) { + if (!isWin$1) { + return; + } + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed); + + if (err) { + return originalEmit.call(cp, 'error', err); + } + } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; +} + +function verifyENOENT(status, parsed) { + if (isWin$1 && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; +} + +function verifyENOENTSync(status, parsed) { + if (isWin$1 && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } + + return null; +} + +var enoent$1 = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; + +const cp = require$$0$1; +const parse = parse_1; +const enoent = enoent$1; + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; +} + +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; +} + +crossSpawn.exports = spawn; +crossSpawn.exports.spawn = spawn; +crossSpawn.exports.sync = spawnSync; + +crossSpawn.exports._parse = parse; +crossSpawn.exports._enoent = enoent; + +var signalExit = {exports: {}}; + +var signals$1 = {exports: {}}; + +var hasRequiredSignals; + +function requireSignals () { + if (hasRequiredSignals) return signals$1.exports; + hasRequiredSignals = 1; + (function (module) { + // This is not the set of all possible signals. + // + // It IS, however, the set of all signals that trigger + // an exit on either Linux or BSD systems. Linux is a + // superset of the signal names supported on BSD, and + // the unknown signals just fail to register, so we can + // catch that easily enough. + // + // Don't bother with SIGKILL. It's uncatchable, which + // means that we can't fire any callbacks anyway. + // + // If a user does happen to register a handler on a non- + // fatal signal like SIGWINCH or something, and then + // exit, it'll end up firing `process.emit('exit')`, so + // the handler will be fired anyway. + // + // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised + // artificially, inherently leave the process in a + // state from which it is not safe to try and enter JS + // listeners. + module.exports = [ + 'SIGABRT', + 'SIGALRM', + 'SIGHUP', + 'SIGINT', + 'SIGTERM' + ]; + + if (process.platform !== 'win32') { + module.exports.push( + 'SIGVTALRM', + 'SIGXCPU', + 'SIGXFSZ', + 'SIGUSR2', + 'SIGTRAP', + 'SIGSYS', + 'SIGQUIT', + 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ); + } + + if (process.platform === 'linux') { + module.exports.push( + 'SIGIO', + 'SIGPOLL', + 'SIGPWR', + 'SIGSTKFLT', + 'SIGUNUSED' + ); + } +} (signals$1)); + return signals$1.exports; +} + +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +// grab a reference to node's real process object right away +var process$1 = commonjsGlobal.process; + +const processOk = function (process) { + return process && + typeof process === 'object' && + typeof process.removeListener === 'function' && + typeof process.emit === 'function' && + typeof process.reallyExit === 'function' && + typeof process.listeners === 'function' && + typeof process.kill === 'function' && + typeof process.pid === 'number' && + typeof process.on === 'function' +}; + +// some kind of non-node environment, just no-op +/* istanbul ignore if */ +if (!processOk(process$1)) { + signalExit.exports = function () { + return function () {} + }; +} else { + var assert = assert$1; + var signals = requireSignals(); + var isWin = /^win/i.test(process$1.platform); + + var EE = require$$2; + /* istanbul ignore if */ + if (typeof EE !== 'function') { + EE = EE.EventEmitter; + } + + var emitter; + if (process$1.__signal_exit_emitter__) { + emitter = process$1.__signal_exit_emitter__; + } else { + emitter = process$1.__signal_exit_emitter__ = new EE(); + emitter.count = 0; + emitter.emitted = {}; + } + + // Because this emitter is a global, we have to check to see if a + // previous version of this library failed to enable infinite listeners. + // I know what you're about to say. But literally everything about + // signal-exit is a compromise with evil. Get used to it. + if (!emitter.infinite) { + emitter.setMaxListeners(Infinity); + emitter.infinite = true; + } + + signalExit.exports = function (cb, opts) { + /* istanbul ignore if */ + if (!processOk(commonjsGlobal.process)) { + return function () {} + } + assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler'); + + if (loaded === false) { + load(); + } + + var ev = 'exit'; + if (opts && opts.alwaysLast) { + ev = 'afterexit'; + } + + var remove = function () { + emitter.removeListener(ev, cb); + if (emitter.listeners('exit').length === 0 && + emitter.listeners('afterexit').length === 0) { + unload(); + } + }; + emitter.on(ev, cb); + + return remove + }; + + var unload = function unload () { + if (!loaded || !processOk(commonjsGlobal.process)) { + return + } + loaded = false; + + signals.forEach(function (sig) { + try { + process$1.removeListener(sig, sigListeners[sig]); + } catch (er) {} + }); + process$1.emit = originalProcessEmit; + process$1.reallyExit = originalProcessReallyExit; + emitter.count -= 1; + }; + signalExit.exports.unload = unload; + + var emit = function emit (event, code, signal) { + /* istanbul ignore if */ + if (emitter.emitted[event]) { + return + } + emitter.emitted[event] = true; + emitter.emit(event, code, signal); + }; + + // { : , ... } + var sigListeners = {}; + signals.forEach(function (sig) { + sigListeners[sig] = function listener () { + /* istanbul ignore if */ + if (!processOk(commonjsGlobal.process)) { + return + } + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + var listeners = process$1.listeners(sig); + if (listeners.length === emitter.count) { + unload(); + emit('exit', null, sig); + /* istanbul ignore next */ + emit('afterexit', null, sig); + /* istanbul ignore next */ + if (isWin && sig === 'SIGHUP') { + // "SIGHUP" throws an `ENOSYS` error on Windows, + // so use a supported signal instead + sig = 'SIGINT'; + } + /* istanbul ignore next */ + process$1.kill(process$1.pid, sig); + } + }; + }); + + signalExit.exports.signals = function () { + return signals + }; + + var loaded = false; + + var load = function load () { + if (loaded || !processOk(commonjsGlobal.process)) { + return + } + loaded = true; + + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + emitter.count += 1; + + signals = signals.filter(function (sig) { + try { + process$1.on(sig, sigListeners[sig]); + return true + } catch (er) { + return false + } + }); + + process$1.emit = processEmit; + process$1.reallyExit = processReallyExit; + }; + signalExit.exports.load = load; + + var originalProcessReallyExit = process$1.reallyExit; + var processReallyExit = function processReallyExit (code) { + /* istanbul ignore if */ + if (!processOk(commonjsGlobal.process)) { + return + } + process$1.exitCode = code || /* istanbul ignore next */ 0; + emit('exit', process$1.exitCode, null); + /* istanbul ignore next */ + emit('afterexit', process$1.exitCode, null); + /* istanbul ignore next */ + originalProcessReallyExit.call(process$1, process$1.exitCode); + }; + + var originalProcessEmit = process$1.emit; + var processEmit = function processEmit (ev, arg) { + if (ev === 'exit' && processOk(commonjsGlobal.process)) { + /* istanbul ignore else */ + if (arg !== undefined) { + process$1.exitCode = arg; + } + var ret = originalProcessEmit.apply(this, arguments); + /* istanbul ignore next */ + emit('exit', process$1.exitCode, null); + /* istanbul ignore next */ + emit('afterexit', process$1.exitCode, null); + /* istanbul ignore next */ + return ret + } else { + return originalProcessEmit.apply(this, arguments) + } + }; +} + +var getStream$1 = {exports: {}}; + +const {PassThrough: PassThroughStream} = require$$0$2; + +var bufferStream$1 = options => { + options = {...options}; + + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; + + if (array) { + objectMode = !(encoding || isBuffer); + } else { + encoding = encoding || 'utf8'; + } + + if (isBuffer) { + encoding = null; + } + + const stream = new PassThroughStream({objectMode}); + + if (encoding) { + stream.setEncoding(encoding); + } + + let length = 0; + const chunks = []; + + stream.on('data', chunk => { + chunks.push(chunk); + + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); + + stream.getBufferedValue = () => { + if (array) { + return chunks; + } + + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; + + stream.getBufferedLength = () => length; + + return stream; +}; + +const {constants: BufferConstants} = require$$0$3; +const stream = require$$0$2; +const {promisify} = util; +const bufferStream = bufferStream$1; + +const streamPipelinePromisified = promisify(stream.pipeline); + +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} + +async function getStream(inputStream, options) { + if (!inputStream) { + throw new Error('Expected a stream'); + } + + options = { + maxBuffer: Infinity, + ...options + }; + + const {maxBuffer} = options; + const stream = bufferStream(options); + + await new Promise((resolve, reject) => { + const rejectPromise = error => { + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { + error.bufferedData = stream.getBufferedValue(); + } + + reject(error); + }; + + (async () => { + try { + await streamPipelinePromisified(inputStream, stream); + resolve(); + } catch (error) { + rejectPromise(error); + } + })(); + + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); + + return stream.getBufferedValue(); +} + +getStream$1.exports = getStream; +getStream$1.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); +getStream$1.exports.array = (stream, options) => getStream(stream, {...options, array: true}); +getStream$1.exports.MaxBufferError = MaxBufferError; + +const { PassThrough } = require$$0$2; + +var mergeStream = function (/*streams...*/) { + var sources = []; + var output = new PassThrough({objectMode: true}); + + output.setMaxListeners(0); + + output.add = add; + output.isEmpty = isEmpty; + + output.on('unpipe', remove); + + Array.prototype.slice.call(arguments).forEach(add); + + return output + + function add (source) { + if (Array.isArray(source)) { + source.forEach(add); + return this + } + + sources.push(source); + source.once('end', remove.bind(null, source)); + source.once('error', output.emit.bind(output, 'error')); + source.pipe(output, {end: false}); + return this + } + + function isEmpty () { + return sources.length == 0; + } + + function remove (source) { + sources = sources.filter(function (it) { return it !== source }); + if (!sources.length && output.readable) { output.end(); } + } +}; + +export { crossSpawn as c, getStream$1 as g, mergeStream as m, pathKey$1 as p, signalExit as s }; diff --git a/node_modules/vitest/dist/vendor-index.9c919048.js b/node_modules/vitest/dist/vendor-index.9c919048.js new file mode 100644 index 0000000..7044cae --- /dev/null +++ b/node_modules/vitest/dist/vendor-index.9c919048.js @@ -0,0 +1,61 @@ +var onetime$1 = {exports: {}}; + +var mimicFn$2 = {exports: {}}; + +const mimicFn$1 = (to, from) => { + for (const prop of Reflect.ownKeys(from)) { + Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); + } + + return to; +}; + +mimicFn$2.exports = mimicFn$1; +// TODO: Remove this for the next major release +mimicFn$2.exports.default = mimicFn$1; + +const mimicFn = mimicFn$2.exports; + +const calledFunctions = new WeakMap(); + +const onetime = (function_, options = {}) => { + if (typeof function_ !== 'function') { + throw new TypeError('Expected a function'); + } + + let returnValue; + let callCount = 0; + const functionName = function_.displayName || function_.name || ''; + + const onetime = function (...arguments_) { + calledFunctions.set(onetime, ++callCount); + + if (callCount === 1) { + returnValue = function_.apply(this, arguments_); + function_ = null; + } else if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } + + return returnValue; + }; + + mimicFn(onetime, function_); + calledFunctions.set(onetime, callCount); + + return onetime; +}; + +onetime$1.exports = onetime; +// TODO: Remove this for the next major release +onetime$1.exports.default = onetime; + +onetime$1.exports.callCount = function_ => { + if (!calledFunctions.has(function_)) { + throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); + } + + return calledFunctions.get(function_); +}; + +export { onetime$1 as o }; diff --git a/node_modules/vitest/dist/vendor-index.9f20a9be.js b/node_modules/vitest/dist/vendor-index.9f20a9be.js new file mode 100644 index 0000000..0451260 --- /dev/null +++ b/node_modules/vitest/dist/vendor-index.9f20a9be.js @@ -0,0 +1,6291 @@ +import require$$0 from 'readline'; +import require$$2 from 'events'; + +function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); +} + +var prompts$2 = {}; + +var kleur; +var hasRequiredKleur; + +function requireKleur () { + if (hasRequiredKleur) return kleur; + hasRequiredKleur = 1; + + const { FORCE_COLOR, NODE_DISABLE_COLORS, TERM } = process.env; + + const $ = { + enabled: !NODE_DISABLE_COLORS && TERM !== 'dumb' && FORCE_COLOR !== '0', + + // modifiers + reset: init(0, 0), + bold: init(1, 22), + dim: init(2, 22), + italic: init(3, 23), + underline: init(4, 24), + inverse: init(7, 27), + hidden: init(8, 28), + strikethrough: init(9, 29), + + // colors + black: init(30, 39), + red: init(31, 39), + green: init(32, 39), + yellow: init(33, 39), + blue: init(34, 39), + magenta: init(35, 39), + cyan: init(36, 39), + white: init(37, 39), + gray: init(90, 39), + grey: init(90, 39), + + // background colors + bgBlack: init(40, 49), + bgRed: init(41, 49), + bgGreen: init(42, 49), + bgYellow: init(43, 49), + bgBlue: init(44, 49), + bgMagenta: init(45, 49), + bgCyan: init(46, 49), + bgWhite: init(47, 49) + }; + + function run(arr, str) { + let i=0, tmp, beg='', end=''; + for (; i < arr.length; i++) { + tmp = arr[i]; + beg += tmp.open; + end += tmp.close; + if (str.includes(tmp.close)) { + str = str.replace(tmp.rgx, tmp.close + tmp.open); + } + } + return beg + str + end; + } + + function chain(has, keys) { + let ctx = { has, keys }; + + ctx.reset = $.reset.bind(ctx); + ctx.bold = $.bold.bind(ctx); + ctx.dim = $.dim.bind(ctx); + ctx.italic = $.italic.bind(ctx); + ctx.underline = $.underline.bind(ctx); + ctx.inverse = $.inverse.bind(ctx); + ctx.hidden = $.hidden.bind(ctx); + ctx.strikethrough = $.strikethrough.bind(ctx); + + ctx.black = $.black.bind(ctx); + ctx.red = $.red.bind(ctx); + ctx.green = $.green.bind(ctx); + ctx.yellow = $.yellow.bind(ctx); + ctx.blue = $.blue.bind(ctx); + ctx.magenta = $.magenta.bind(ctx); + ctx.cyan = $.cyan.bind(ctx); + ctx.white = $.white.bind(ctx); + ctx.gray = $.gray.bind(ctx); + ctx.grey = $.grey.bind(ctx); + + ctx.bgBlack = $.bgBlack.bind(ctx); + ctx.bgRed = $.bgRed.bind(ctx); + ctx.bgGreen = $.bgGreen.bind(ctx); + ctx.bgYellow = $.bgYellow.bind(ctx); + ctx.bgBlue = $.bgBlue.bind(ctx); + ctx.bgMagenta = $.bgMagenta.bind(ctx); + ctx.bgCyan = $.bgCyan.bind(ctx); + ctx.bgWhite = $.bgWhite.bind(ctx); + + return ctx; + } + + function init(open, close) { + let blk = { + open: `\x1b[${open}m`, + close: `\x1b[${close}m`, + rgx: new RegExp(`\\x1b\\[${close}m`, 'g') + }; + return function (txt) { + if (this !== void 0 && this.has !== void 0) { + this.has.includes(open) || (this.has.push(open),this.keys.push(blk)); + return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+''; + } + return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+''; + }; + } + + kleur = $; + return kleur; +} + +var action$1; +var hasRequiredAction$1; + +function requireAction$1 () { + if (hasRequiredAction$1) return action$1; + hasRequiredAction$1 = 1; + + action$1 = (key, isSelect) => { + if (key.meta && key.name !== 'escape') return; + + if (key.ctrl) { + if (key.name === 'a') return 'first'; + if (key.name === 'c') return 'abort'; + if (key.name === 'd') return 'abort'; + if (key.name === 'e') return 'last'; + if (key.name === 'g') return 'reset'; + } + + if (isSelect) { + if (key.name === 'j') return 'down'; + if (key.name === 'k') return 'up'; + } + + if (key.name === 'return') return 'submit'; + if (key.name === 'enter') return 'submit'; // ctrl + J + + if (key.name === 'backspace') return 'delete'; + if (key.name === 'delete') return 'deleteForward'; + if (key.name === 'abort') return 'abort'; + if (key.name === 'escape') return 'exit'; + if (key.name === 'tab') return 'next'; + if (key.name === 'pagedown') return 'nextPage'; + if (key.name === 'pageup') return 'prevPage'; // TODO create home() in prompt types (e.g. TextPrompt) + + if (key.name === 'home') return 'home'; // TODO create end() in prompt types (e.g. TextPrompt) + + if (key.name === 'end') return 'end'; + if (key.name === 'up') return 'up'; + if (key.name === 'down') return 'down'; + if (key.name === 'right') return 'right'; + if (key.name === 'left') return 'left'; + return false; + }; + return action$1; +} + +var strip$1; +var hasRequiredStrip$1; + +function requireStrip$1 () { + if (hasRequiredStrip$1) return strip$1; + hasRequiredStrip$1 = 1; + + strip$1 = str => { + const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'].join('|'); + const RGX = new RegExp(pattern, 'g'); + return typeof str === 'string' ? str.replace(RGX, '') : str; + }; + return strip$1; +} + +var src; +var hasRequiredSrc; + +function requireSrc () { + if (hasRequiredSrc) return src; + hasRequiredSrc = 1; + + const ESC = '\x1B'; + const CSI = `${ESC}[`; + const beep = '\u0007'; + + const cursor = { + to(x, y) { + if (!y) return `${CSI}${x + 1}G`; + return `${CSI}${y + 1};${x + 1}H`; + }, + move(x, y) { + let ret = ''; + + if (x < 0) ret += `${CSI}${-x}D`; + else if (x > 0) ret += `${CSI}${x}C`; + + if (y < 0) ret += `${CSI}${-y}A`; + else if (y > 0) ret += `${CSI}${y}B`; + + return ret; + }, + up: (count = 1) => `${CSI}${count}A`, + down: (count = 1) => `${CSI}${count}B`, + forward: (count = 1) => `${CSI}${count}C`, + backward: (count = 1) => `${CSI}${count}D`, + nextLine: (count = 1) => `${CSI}E`.repeat(count), + prevLine: (count = 1) => `${CSI}F`.repeat(count), + left: `${CSI}G`, + hide: `${CSI}?25l`, + show: `${CSI}?25h`, + save: `${ESC}7`, + restore: `${ESC}8` + }; + + const scroll = { + up: (count = 1) => `${CSI}S`.repeat(count), + down: (count = 1) => `${CSI}T`.repeat(count) + }; + + const erase = { + screen: `${CSI}2J`, + up: (count = 1) => `${CSI}1J`.repeat(count), + down: (count = 1) => `${CSI}J`.repeat(count), + line: `${CSI}2K`, + lineEnd: `${CSI}K`, + lineStart: `${CSI}1K`, + lines(count) { + let clear = ''; + for (let i = 0; i < count; i++) + clear += this.line + (i < count - 1 ? cursor.up() : ''); + if (count) + clear += cursor.left; + return clear; + } + }; + + src = { cursor, scroll, erase, beep }; + return src; +} + +var clear$1; +var hasRequiredClear$1; + +function requireClear$1 () { + if (hasRequiredClear$1) return clear$1; + hasRequiredClear$1 = 1; + + function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + + 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; } + + const strip = requireStrip$1(); + + const _require = requireSrc(), + erase = _require.erase, + cursor = _require.cursor; + + const width = str => [...strip(str)].length; + /** + * @param {string} prompt + * @param {number} perLine + */ + + + clear$1 = function (prompt, perLine) { + if (!perLine) return erase.line + cursor.to(0); + let rows = 0; + const lines = prompt.split(/\r?\n/); + + var _iterator = _createForOfIteratorHelper(lines), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + let line = _step.value; + rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return erase.lines(rows); + }; + return clear$1; +} + +var figures_1$1; +var hasRequiredFigures$1; + +function requireFigures$1 () { + if (hasRequiredFigures$1) return figures_1$1; + hasRequiredFigures$1 = 1; + + const main = { + arrowUp: '↑', + arrowDown: '↓', + arrowLeft: '←', + arrowRight: '→', + radioOn: '◉', + radioOff: '◯', + tick: '✔', + cross: '✖', + ellipsis: '…', + pointerSmall: '›', + line: '─', + pointer: '❯' + }; + const win = { + arrowUp: main.arrowUp, + arrowDown: main.arrowDown, + arrowLeft: main.arrowLeft, + arrowRight: main.arrowRight, + radioOn: '(*)', + radioOff: '( )', + tick: '√', + cross: '×', + ellipsis: '...', + pointerSmall: '»', + line: '─', + pointer: '>' + }; + const figures = process.platform === 'win32' ? win : main; + figures_1$1 = figures; + return figures_1$1; +} + +var style$1; +var hasRequiredStyle$1; + +function requireStyle$1 () { + if (hasRequiredStyle$1) return style$1; + hasRequiredStyle$1 = 1; + + const c = requireKleur(); + + const figures = requireFigures$1(); // rendering user input. + + + const styles = Object.freeze({ + password: { + scale: 1, + render: input => '*'.repeat(input.length) + }, + emoji: { + scale: 2, + render: input => '😃'.repeat(input.length) + }, + invisible: { + scale: 0, + render: input => '' + }, + default: { + scale: 1, + render: input => `${input}` + } + }); + + const render = type => styles[type] || styles.default; // icon to signalize a prompt. + + + const symbols = Object.freeze({ + aborted: c.red(figures.cross), + done: c.green(figures.tick), + exited: c.yellow(figures.cross), + default: c.cyan('?') + }); + + const symbol = (done, aborted, exited) => aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default; // between the question and the user's input. + + + const delimiter = completing => c.gray(completing ? figures.ellipsis : figures.pointerSmall); + + const item = (expandable, expanded) => c.gray(expandable ? expanded ? figures.pointerSmall : '+' : figures.line); + + style$1 = { + styles, + render, + symbols, + symbol, + delimiter, + item + }; + return style$1; +} + +var lines$1; +var hasRequiredLines$1; + +function requireLines$1 () { + if (hasRequiredLines$1) return lines$1; + hasRequiredLines$1 = 1; + + const strip = requireStrip$1(); + /** + * @param {string} msg + * @param {number} perLine + */ + + + lines$1 = function (msg, perLine) { + let lines = String(strip(msg) || '').split(/\r?\n/); + if (!perLine) return lines.length; + return lines.map(l => Math.ceil(l.length / perLine)).reduce((a, b) => a + b); + }; + return lines$1; +} + +var wrap$1; +var hasRequiredWrap$1; + +function requireWrap$1 () { + if (hasRequiredWrap$1) return wrap$1; + hasRequiredWrap$1 = 1; + /** + * @param {string} msg The message to wrap + * @param {object} opts + * @param {number|string} [opts.margin] Left margin + * @param {number} opts.width Maximum characters per line including the margin + */ + + wrap$1 = (msg, opts = {}) => { + const tab = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(' ').join('') : opts.margin || ''; + const width = opts.width; + return (msg || '').split(/\r?\n/g).map(line => line.split(/\s+/g).reduce((arr, w) => { + if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width) arr[arr.length - 1] += ` ${w}`;else arr.push(`${tab}${w}`); + return arr; + }, [tab]).join('\n')).join('\n'); + }; + return wrap$1; +} + +var entriesToDisplay$1; +var hasRequiredEntriesToDisplay$1; + +function requireEntriesToDisplay$1 () { + if (hasRequiredEntriesToDisplay$1) return entriesToDisplay$1; + hasRequiredEntriesToDisplay$1 = 1; + /** + * Determine what entries should be displayed on the screen, based on the + * currently selected index and the maximum visible. Used in list-based + * prompts like `select` and `multiselect`. + * + * @param {number} cursor the currently selected entry + * @param {number} total the total entries available to display + * @param {number} [maxVisible] the number of entries that can be displayed + */ + + entriesToDisplay$1 = (cursor, total, maxVisible) => { + maxVisible = maxVisible || total; + let startIndex = Math.min(total - maxVisible, cursor - Math.floor(maxVisible / 2)); + if (startIndex < 0) startIndex = 0; + let endIndex = Math.min(startIndex + maxVisible, total); + return { + startIndex, + endIndex + }; + }; + return entriesToDisplay$1; +} + +var util$1; +var hasRequiredUtil$1; + +function requireUtil$1 () { + if (hasRequiredUtil$1) return util$1; + hasRequiredUtil$1 = 1; + + util$1 = { + action: requireAction$1(), + clear: requireClear$1(), + style: requireStyle$1(), + strip: requireStrip$1(), + figures: requireFigures$1(), + lines: requireLines$1(), + wrap: requireWrap$1(), + entriesToDisplay: requireEntriesToDisplay$1() + }; + return util$1; +} + +var prompt$1; +var hasRequiredPrompt$1; + +function requirePrompt$1 () { + if (hasRequiredPrompt$1) return prompt$1; + hasRequiredPrompt$1 = 1; + + const readline = require$$0; + + const _require = requireUtil$1(), + action = _require.action; + + const EventEmitter = require$$2; + + const _require2 = requireSrc(), + beep = _require2.beep, + cursor = _require2.cursor; + + const color = requireKleur(); + /** + * Base prompt skeleton + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + + class Prompt extends EventEmitter { + constructor(opts = {}) { + super(); + this.firstRender = true; + this.in = opts.stdin || process.stdin; + this.out = opts.stdout || process.stdout; + + this.onRender = (opts.onRender || (() => void 0)).bind(this); + + const rl = readline.createInterface({ + input: this.in, + escapeCodeTimeout: 50 + }); + readline.emitKeypressEvents(this.in, rl); + if (this.in.isTTY) this.in.setRawMode(true); + const isSelect = ['SelectPrompt', 'MultiselectPrompt'].indexOf(this.constructor.name) > -1; + + const keypress = (str, key) => { + let a = action(key, isSelect); + + if (a === false) { + this._ && this._(str, key); + } else if (typeof this[a] === 'function') { + this[a](key); + } else { + this.bell(); + } + }; + + this.close = () => { + this.out.write(cursor.show); + this.in.removeListener('keypress', keypress); + if (this.in.isTTY) this.in.setRawMode(false); + rl.close(); + this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value); + this.closed = true; + }; + + this.in.on('keypress', keypress); + } + + fire() { + this.emit('state', { + value: this.value, + aborted: !!this.aborted, + exited: !!this.exited + }); + } + + bell() { + this.out.write(beep); + } + + render() { + this.onRender(color); + if (this.firstRender) this.firstRender = false; + } + + } + + prompt$1 = Prompt; + return prompt$1; +} + +var text$1; +var hasRequiredText$1; + +function requireText$1 () { + if (hasRequiredText$1) return text$1; + hasRequiredText$1 = 1; + + 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 color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireSrc(), + erase = _require.erase, + cursor = _require.cursor; + + const _require2 = requireUtil$1(), + style = _require2.style, + clear = _require2.clear, + lines = _require2.lines, + figures = _require2.figures; + /** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.initial] Default value + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ + + + class TextPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.msg = opts.message; + this.initial = opts.initial || ``; + + this.validator = opts.validate || (() => true); + + this.value = ``; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.clear = clear(``, this.out.columns); + this.render(); + } + + set value(v) { + if (!v && this.initial) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(this.initial)); + } else { + this.placeholder = false; + this.rendered = this.transform.render(v); + } + + this._value = v; + this.fire(); + } + + get value() { + return this._value; + } + + reset() { + this.value = ``; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.value = this.value || this.initial; + this.done = this.aborted = true; + this.error = false; + this.red = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + validate() { + var _this = this; + + return _asyncToGenerator(function* () { + let valid = yield _this.validator(_this.value); + + if (typeof valid === `string`) { + _this.errorMsg = valid; + valid = false; + } + + _this.error = !valid; + })(); + } + + submit() { + var _this2 = this; + + return _asyncToGenerator(function* () { + _this2.value = _this2.value || _this2.initial; + _this2.cursorOffset = 0; + _this2.cursor = _this2.rendered.length; + yield _this2.validate(); + + if (_this2.error) { + _this2.red = true; + + _this2.fire(); + + _this2.render(); + + return; + } + + _this2.done = true; + _this2.aborted = false; + + _this2.fire(); + + _this2.render(); + + _this2.out.write('\n'); + + _this2.close(); + })(); + } + + next() { + if (!this.placeholder) return this.bell(); + this.value = this.initial; + this.cursor = this.rendered.length; + this.fire(); + this.render(); + } + + moveCursor(n) { + if (this.placeholder) return; + this.cursor = this.cursor + n; + this.cursorOffset += n; + } + + _(c, key) { + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${c}${s2}`; + this.red = false; + this.cursor = this.placeholder ? 0 : s1.length + 1; + this.render(); + } + + delete() { + if (this.isCursorAtStart()) return this.bell(); + let s1 = this.value.slice(0, this.cursor - 1); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${s2}`; + this.red = false; + + if (this.isCursorAtStart()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + this.moveCursor(-1); + } + + this.render(); + } + + deleteForward() { + if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell(); + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor + 1); + this.value = `${s1}${s2}`; + this.red = false; + + if (this.isCursorAtEnd()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + } + + this.render(); + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length; + this.render(); + } + + left() { + if (this.cursor <= 0 || this.placeholder) return this.bell(); + this.moveCursor(-1); + this.render(); + } + + right() { + if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell(); + this.moveCursor(1); + this.render(); + } + + isCursorAtStart() { + return this.cursor === 0 || this.placeholder && this.cursor === 1; + } + + isCursorAtEnd() { + return this.cursor === this.rendered.length || this.placeholder && this.cursor === this.rendered.length + 1; + } + + render() { + if (this.closed) return; + + if (!this.firstRender) { + if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + + super.render(); + this.outputError = ''; + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.red ? color.red(this.rendered) : this.rendered].join(` `); + + if (this.error) { + this.outputError += this.errorMsg.split(`\n`).reduce((a, l, i) => a + `\n${i ? ' ' : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0)); + } + + } + + text$1 = TextPrompt; + return text$1; +} + +var select$1; +var hasRequiredSelect$1; + +function requireSelect$1 () { + if (hasRequiredSelect$1) return select$1; + hasRequiredSelect$1 = 1; + + const color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireUtil$1(), + style = _require.style, + clear = _require.clear, + figures = _require.figures, + wrap = _require.wrap, + entriesToDisplay = _require.entriesToDisplay; + + const _require2 = requireSrc(), + cursor = _require2.cursor; + /** + * SelectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {Number} [opts.initial] Index of default value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + */ + + + class SelectPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.hint = opts.hint || '- Use arrow-keys. Return to submit.'; + this.warn = opts.warn || '- This option is disabled'; + this.cursor = opts.initial || 0; + this.choices = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') ch = { + title: ch, + value: idx + }; + return { + title: ch && (ch.title || ch.value || ch), + value: ch && (ch.value === undefined ? idx : ch.value), + description: ch && ch.description, + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = (this.choices[this.cursor] || {}).value; + this.clear = clear('', this.out.columns); + this.render(); + } + + moveCursor(n) { + this.cursor = n; + this.value = this.choices[n].value; + this.fire(); + } + + reset() { + this.moveCursor(0); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + if (!this.selection.disabled) { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } else this.bell(); + } + + first() { + this.moveCursor(0); + this.render(); + } + + last() { + this.moveCursor(this.choices.length - 1); + this.render(); + } + + up() { + if (this.cursor === 0) { + this.moveCursor(this.choices.length - 1); + } else { + this.moveCursor(this.cursor - 1); + } + + this.render(); + } + + down() { + if (this.cursor === this.choices.length - 1) { + this.moveCursor(0); + } else { + this.moveCursor(this.cursor + 1); + } + + this.render(); + } + + next() { + this.moveCursor((this.cursor + 1) % this.choices.length); + this.render(); + } + + _(c, key) { + if (c === ' ') return this.submit(); + } + + get selection() { + return this.choices[this.cursor]; + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let _entriesToDisplay = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage), + startIndex = _entriesToDisplay.startIndex, + endIndex = _entriesToDisplay.endIndex; // Print prompt + + + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.done ? this.selection.title : this.selection.disabled ? color.yellow(this.warn) : color.gray(this.hint)].join(' '); // Print choices + + if (!this.done) { + this.outputText += '\n'; + + for (let i = startIndex; i < endIndex; i++) { + let title, + prefix, + desc = '', + v = this.choices[i]; // Determine whether to display "more choices" indicators + + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < this.choices.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + + if (v.disabled) { + title = this.cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + prefix = (this.cursor === i ? color.bold().gray(figures.pointer) + ' ' : ' ') + prefix; + } else { + title = this.cursor === i ? color.cyan().underline(v.title) : v.title; + prefix = (this.cursor === i ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + + if (v.description && this.cursor === i) { + desc = ` - ${v.description}`; + + if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { + margin: 3, + width: this.out.columns + }); + } + } + } + + this.outputText += `${prefix} ${title}${color.gray(desc)}\n`; + } + } + + this.out.write(this.outputText); + } + + } + + select$1 = SelectPrompt; + return select$1; +} + +var toggle$1; +var hasRequiredToggle$1; + +function requireToggle$1 () { + if (hasRequiredToggle$1) return toggle$1; + hasRequiredToggle$1 = 1; + + const color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireUtil$1(), + style = _require.style, + clear = _require.clear; + + const _require2 = requireSrc(), + cursor = _require2.cursor, + erase = _require2.erase; + /** + * TogglePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial=false] Default value + * @param {String} [opts.active='no'] Active label + * @param {String} [opts.inactive='off'] Inactive label + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + + class TogglePrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.value = !!opts.initial; + this.active = opts.active || 'on'; + this.inactive = opts.inactive || 'off'; + this.initialValue = this.value; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + deactivate() { + if (this.value === false) return this.bell(); + this.value = false; + this.render(); + } + + activate() { + if (this.value === true) return this.bell(); + this.value = true; + this.render(); + } + + delete() { + this.deactivate(); + } + + left() { + this.deactivate(); + } + + right() { + this.activate(); + } + + down() { + this.deactivate(); + } + + up() { + this.activate(); + } + + next() { + this.value = !this.value; + this.fire(); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.value = !this.value; + } else if (c === '1') { + this.value = true; + } else if (c === '0') { + this.value = false; + } else return this.bell(); + + this.render(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.value ? this.inactive : color.cyan().underline(this.inactive), color.gray('/'), this.value ? color.cyan().underline(this.active) : this.active].join(' '); + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + + } + + toggle$1 = TogglePrompt; + return toggle$1; +} + +var datepart$1; +var hasRequiredDatepart$1; + +function requireDatepart$1 () { + if (hasRequiredDatepart$1) return datepart$1; + hasRequiredDatepart$1 = 1; + + class DatePart { + constructor({ + token, + date, + parts, + locales + }) { + this.token = token; + this.date = date || new Date(); + this.parts = parts || [this]; + this.locales = locales || {}; + } + + up() {} + + down() {} + + next() { + const currentIdx = this.parts.indexOf(this); + return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + setTo(val) {} + + prev() { + let parts = [].concat(this.parts).reverse(); + const currentIdx = parts.indexOf(this); + return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + toString() { + return String(this.date); + } + + } + + datepart$1 = DatePart; + return datepart$1; +} + +var meridiem$1; +var hasRequiredMeridiem$1; + +function requireMeridiem$1 () { + if (hasRequiredMeridiem$1) return meridiem$1; + hasRequiredMeridiem$1 = 1; + + const DatePart = requireDatepart$1(); + + class Meridiem extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setHours((this.date.getHours() + 12) % 24); + } + + down() { + this.up(); + } + + toString() { + let meridiem = this.date.getHours() > 12 ? 'pm' : 'am'; + return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem; + } + + } + + meridiem$1 = Meridiem; + return meridiem$1; +} + +var day$1; +var hasRequiredDay$1; + +function requireDay$1 () { + if (hasRequiredDay$1) return day$1; + hasRequiredDay$1 = 1; + + const DatePart = requireDatepart$1(); + + const pos = n => { + n = n % 10; + return n === 1 ? 'st' : n === 2 ? 'nd' : n === 3 ? 'rd' : 'th'; + }; + + class Day extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setDate(this.date.getDate() + 1); + } + + down() { + this.date.setDate(this.date.getDate() - 1); + } + + setTo(val) { + this.date.setDate(parseInt(val.substr(-2))); + } + + toString() { + let date = this.date.getDate(); + let day = this.date.getDay(); + return this.token === 'DD' ? String(date).padStart(2, '0') : this.token === 'Do' ? date + pos(date) : this.token === 'd' ? day + 1 : this.token === 'ddd' ? this.locales.weekdaysShort[day] : this.token === 'dddd' ? this.locales.weekdays[day] : date; + } + + } + + day$1 = Day; + return day$1; +} + +var hours$1; +var hasRequiredHours$1; + +function requireHours$1 () { + if (hasRequiredHours$1) return hours$1; + hasRequiredHours$1 = 1; + + const DatePart = requireDatepart$1(); + + class Hours extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setHours(this.date.getHours() + 1); + } + + down() { + this.date.setHours(this.date.getHours() - 1); + } + + setTo(val) { + this.date.setHours(parseInt(val.substr(-2))); + } + + toString() { + let hours = this.date.getHours(); + if (/h/.test(this.token)) hours = hours % 12 || 12; + return this.token.length > 1 ? String(hours).padStart(2, '0') : hours; + } + + } + + hours$1 = Hours; + return hours$1; +} + +var milliseconds$1; +var hasRequiredMilliseconds$1; + +function requireMilliseconds$1 () { + if (hasRequiredMilliseconds$1) return milliseconds$1; + hasRequiredMilliseconds$1 = 1; + + const DatePart = requireDatepart$1(); + + class Milliseconds extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setMilliseconds(this.date.getMilliseconds() + 1); + } + + down() { + this.date.setMilliseconds(this.date.getMilliseconds() - 1); + } + + setTo(val) { + this.date.setMilliseconds(parseInt(val.substr(-this.token.length))); + } + + toString() { + return String(this.date.getMilliseconds()).padStart(4, '0').substr(0, this.token.length); + } + + } + + milliseconds$1 = Milliseconds; + return milliseconds$1; +} + +var minutes$1; +var hasRequiredMinutes$1; + +function requireMinutes$1 () { + if (hasRequiredMinutes$1) return minutes$1; + hasRequiredMinutes$1 = 1; + + const DatePart = requireDatepart$1(); + + class Minutes extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setMinutes(this.date.getMinutes() + 1); + } + + down() { + this.date.setMinutes(this.date.getMinutes() - 1); + } + + setTo(val) { + this.date.setMinutes(parseInt(val.substr(-2))); + } + + toString() { + let m = this.date.getMinutes(); + return this.token.length > 1 ? String(m).padStart(2, '0') : m; + } + + } + + minutes$1 = Minutes; + return minutes$1; +} + +var month$1; +var hasRequiredMonth$1; + +function requireMonth$1 () { + if (hasRequiredMonth$1) return month$1; + hasRequiredMonth$1 = 1; + + const DatePart = requireDatepart$1(); + + class Month extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setMonth(this.date.getMonth() + 1); + } + + down() { + this.date.setMonth(this.date.getMonth() - 1); + } + + setTo(val) { + val = parseInt(val.substr(-2)) - 1; + this.date.setMonth(val < 0 ? 0 : val); + } + + toString() { + let month = this.date.getMonth(); + let tl = this.token.length; + return tl === 2 ? String(month + 1).padStart(2, '0') : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1); + } + + } + + month$1 = Month; + return month$1; +} + +var seconds$1; +var hasRequiredSeconds$1; + +function requireSeconds$1 () { + if (hasRequiredSeconds$1) return seconds$1; + hasRequiredSeconds$1 = 1; + + const DatePart = requireDatepart$1(); + + class Seconds extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setSeconds(this.date.getSeconds() + 1); + } + + down() { + this.date.setSeconds(this.date.getSeconds() - 1); + } + + setTo(val) { + this.date.setSeconds(parseInt(val.substr(-2))); + } + + toString() { + let s = this.date.getSeconds(); + return this.token.length > 1 ? String(s).padStart(2, '0') : s; + } + + } + + seconds$1 = Seconds; + return seconds$1; +} + +var year$1; +var hasRequiredYear$1; + +function requireYear$1 () { + if (hasRequiredYear$1) return year$1; + hasRequiredYear$1 = 1; + + const DatePart = requireDatepart$1(); + + class Year extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setFullYear(this.date.getFullYear() + 1); + } + + down() { + this.date.setFullYear(this.date.getFullYear() - 1); + } + + setTo(val) { + this.date.setFullYear(val.substr(-4)); + } + + toString() { + let year = String(this.date.getFullYear()).padStart(4, '0'); + return this.token.length === 2 ? year.substr(-2) : year; + } + + } + + year$1 = Year; + return year$1; +} + +var dateparts$1; +var hasRequiredDateparts$1; + +function requireDateparts$1 () { + if (hasRequiredDateparts$1) return dateparts$1; + hasRequiredDateparts$1 = 1; + + dateparts$1 = { + DatePart: requireDatepart$1(), + Meridiem: requireMeridiem$1(), + Day: requireDay$1(), + Hours: requireHours$1(), + Milliseconds: requireMilliseconds$1(), + Minutes: requireMinutes$1(), + Month: requireMonth$1(), + Seconds: requireSeconds$1(), + Year: requireYear$1() + }; + return dateparts$1; +} + +var date$1; +var hasRequiredDate$1; + +function requireDate$1 () { + if (hasRequiredDate$1) return date$1; + hasRequiredDate$1 = 1; + + 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 color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireUtil$1(), + style = _require.style, + clear = _require.clear, + figures = _require.figures; + + const _require2 = requireSrc(), + erase = _require2.erase, + cursor = _require2.cursor; + + const _require3 = requireDateparts$1(), + DatePart = _require3.DatePart, + Meridiem = _require3.Meridiem, + Day = _require3.Day, + Hours = _require3.Hours, + Milliseconds = _require3.Milliseconds, + Minutes = _require3.Minutes, + Month = _require3.Month, + Seconds = _require3.Seconds, + Year = _require3.Year; + + const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g; + const regexGroups = { + 1: ({ + token + }) => token.replace(/\\(.)/g, '$1'), + 2: opts => new Day(opts), + // Day // TODO + 3: opts => new Month(opts), + // Month + 4: opts => new Year(opts), + // Year + 5: opts => new Meridiem(opts), + // AM/PM // TODO (special) + 6: opts => new Hours(opts), + // Hours + 7: opts => new Minutes(opts), + // Minutes + 8: opts => new Seconds(opts), + // Seconds + 9: opts => new Milliseconds(opts) // Fractional seconds + + }; + const dfltLocales = { + months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','), + monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), + weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), + weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',') + }; + /** + * DatePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Number} [opts.initial] Index of default value + * @param {String} [opts.mask] The format mask + * @param {object} [opts.locales] The date locales + * @param {String} [opts.error] The error message shown on invalid value + * @param {Function} [opts.validate] Function to validate the submitted value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + class DatePrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.cursor = 0; + this.typed = ''; + this.locales = Object.assign(dfltLocales, opts.locales); + this._date = opts.initial || new Date(); + this.errorMsg = opts.error || 'Please Enter A Valid Value'; + + this.validator = opts.validate || (() => true); + + this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss'; + this.clear = clear('', this.out.columns); + this.render(); + } + + get value() { + return this.date; + } + + get date() { + return this._date; + } + + set date(date) { + if (date) this._date.setTime(date.getTime()); + } + + set mask(mask) { + let result; + this.parts = []; + + while (result = regex.exec(mask)) { + let match = result.shift(); + let idx = result.findIndex(gr => gr != null); + this.parts.push(idx in regexGroups ? regexGroups[idx]({ + token: result[idx] || match, + date: this.date, + parts: this.parts, + locales: this.locales + }) : result[idx] || match); + } + + let parts = this.parts.reduce((arr, i) => { + if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') arr[arr.length - 1] += i;else arr.push(i); + return arr; + }, []); + this.parts.splice(0); + this.parts.push(...parts); + this.reset(); + } + + moveCursor(n) { + this.typed = ''; + this.cursor = n; + this.fire(); + } + + reset() { + this.moveCursor(this.parts.findIndex(p => p instanceof DatePart)); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + validate() { + var _this = this; + + return _asyncToGenerator(function* () { + let valid = yield _this.validator(_this.value); + + if (typeof valid === 'string') { + _this.errorMsg = valid; + valid = false; + } + + _this.error = !valid; + })(); + } + + submit() { + var _this2 = this; + + return _asyncToGenerator(function* () { + yield _this2.validate(); + + if (_this2.error) { + _this2.color = 'red'; + + _this2.fire(); + + _this2.render(); + + return; + } + + _this2.done = true; + _this2.aborted = false; + + _this2.fire(); + + _this2.render(); + + _this2.out.write('\n'); + + _this2.close(); + })(); + } + + up() { + this.typed = ''; + this.parts[this.cursor].up(); + this.render(); + } + + down() { + this.typed = ''; + this.parts[this.cursor].down(); + this.render(); + } + + left() { + let prev = this.parts[this.cursor].prev(); + if (prev == null) return this.bell(); + this.moveCursor(this.parts.indexOf(prev)); + this.render(); + } + + right() { + let next = this.parts[this.cursor].next(); + if (next == null) return this.bell(); + this.moveCursor(this.parts.indexOf(next)); + this.render(); + } + + next() { + let next = this.parts[this.cursor].next(); + this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex(part => part instanceof DatePart)); + this.render(); + } + + _(c) { + if (/\d/.test(c)) { + this.typed += c; + this.parts[this.cursor].setTo(this.typed); + this.render(); + } + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); // Print prompt + + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), []).join('')].join(' '); // Print error + + if (this.error) { + this.outputText += this.errorMsg.split('\n').reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + + } + + date$1 = DatePrompt; + return date$1; +} + +var number$1; +var hasRequiredNumber$1; + +function requireNumber$1 () { + if (hasRequiredNumber$1) return number$1; + hasRequiredNumber$1 = 1; + + 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 color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireSrc(), + cursor = _require.cursor, + erase = _require.erase; + + const _require2 = requireUtil$1(), + style = _require2.style, + figures = _require2.figures, + clear = _require2.clear, + lines = _require2.lines; + + const isNumber = /[0-9]/; + + const isDef = any => any !== undefined; + + const round = (number, precision) => { + let factor = Math.pow(10, precision); + return Math.round(number * factor) / factor; + }; + /** + * NumberPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {Number} [opts.initial] Default value + * @param {Number} [opts.max=+Infinity] Max value + * @param {Number} [opts.min=-Infinity] Min value + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ + + + class NumberPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.transform = style.render(opts.style); + this.msg = opts.message; + this.initial = isDef(opts.initial) ? opts.initial : ''; + this.float = !!opts.float; + this.round = opts.round || 2; + this.inc = opts.increment || 1; + this.min = isDef(opts.min) ? opts.min : -Infinity; + this.max = isDef(opts.max) ? opts.max : Infinity; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + + this.validator = opts.validate || (() => true); + + this.color = `cyan`; + this.value = ``; + this.typed = ``; + this.lastHit = 0; + this.render(); + } + + set value(v) { + if (!v && v !== 0) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(`${this.initial}`)); + this._value = ``; + } else { + this.placeholder = false; + this.rendered = this.transform.render(`${round(v, this.round)}`); + this._value = round(v, this.round); + } + + this.fire(); + } + + get value() { + return this._value; + } + + parse(x) { + return this.float ? parseFloat(x) : parseInt(x); + } + + valid(c) { + return c === `-` || c === `.` && this.float || isNumber.test(c); + } + + reset() { + this.typed = ``; + this.value = ``; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + let x = this.value; + this.value = x !== `` ? x : this.initial; + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write(`\n`); + this.close(); + } + + validate() { + var _this = this; + + return _asyncToGenerator(function* () { + let valid = yield _this.validator(_this.value); + + if (typeof valid === `string`) { + _this.errorMsg = valid; + valid = false; + } + + _this.error = !valid; + })(); + } + + submit() { + var _this2 = this; + + return _asyncToGenerator(function* () { + yield _this2.validate(); + + if (_this2.error) { + _this2.color = `red`; + + _this2.fire(); + + _this2.render(); + + return; + } + + let x = _this2.value; + _this2.value = x !== `` ? x : _this2.initial; + _this2.done = true; + _this2.aborted = false; + _this2.error = false; + + _this2.fire(); + + _this2.render(); + + _this2.out.write(`\n`); + + _this2.close(); + })(); + } + + up() { + this.typed = ``; + + if (this.value === '') { + this.value = this.min - this.inc; + } + + if (this.value >= this.max) return this.bell(); + this.value += this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + down() { + this.typed = ``; + + if (this.value === '') { + this.value = this.min + this.inc; + } + + if (this.value <= this.min) return this.bell(); + this.value -= this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + delete() { + let val = this.value.toString(); + if (val.length === 0) return this.bell(); + this.value = this.parse(val = val.slice(0, -1)) || ``; + + if (this.value !== '' && this.value < this.min) { + this.value = this.min; + } + + this.color = `cyan`; + this.fire(); + this.render(); + } + + next() { + this.value = this.initial; + this.fire(); + this.render(); + } + + _(c, key) { + if (!this.valid(c)) return this.bell(); + const now = Date.now(); + if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed + + this.typed += c; + this.lastHit = now; + this.color = `cyan`; + if (c === `.`) return this.fire(); + this.value = Math.min(this.parse(this.typed), this.max); + if (this.value > this.max) this.value = this.max; + if (this.value < this.min) this.value = this.min; + this.fire(); + this.render(); + } + + render() { + if (this.closed) return; + + if (!this.firstRender) { + if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + + super.render(); + this.outputError = ''; // Print prompt + + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), !this.done || !this.done && !this.placeholder ? color[this.color]().underline(this.rendered) : this.rendered].join(` `); // Print error + + if (this.error) { + this.outputError += this.errorMsg.split(`\n`).reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore); + } + + } + + number$1 = NumberPrompt; + return number$1; +} + +var multiselect$1; +var hasRequiredMultiselect$1; + +function requireMultiselect$1 () { + if (hasRequiredMultiselect$1) return multiselect$1; + hasRequiredMultiselect$1 = 1; + + const color = requireKleur(); + + const _require = requireSrc(), + cursor = _require.cursor; + + const Prompt = requirePrompt$1(); + + const _require2 = requireUtil$1(), + clear = _require2.clear, + figures = _require2.figures, + style = _require2.style, + wrap = _require2.wrap, + entriesToDisplay = _require2.entriesToDisplay; + /** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + + class MultiselectPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.cursor = opts.cursor || 0; + this.scrollIndex = opts.cursor || 0; + this.hint = opts.hint || ''; + this.warn = opts.warn || '- This option is disabled -'; + this.minSelected = opts.min; + this.showMinError = false; + this.maxChoices = opts.max; + this.instructions = opts.instructions; + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') ch = { + title: ch, + value: idx + }; + return { + title: ch && (ch.title || ch.value || ch), + description: ch && ch.description, + value: ch && (ch.value === undefined ? idx : ch.value), + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.clear = clear('', this.out.columns); + + if (!opts.overrideRender) { + this.render(); + } + } + + reset() { + this.value.map(v => !v.selected); + this.cursor = 0; + this.fire(); + this.render(); + } + + selected() { + return this.value.filter(v => v.selected); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + const selected = this.value.filter(e => e.selected); + + if (this.minSelected && selected.length < this.minSelected) { + this.showMinError = true; + this.render(); + } else { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length - 1; + this.render(); + } + + next() { + this.cursor = (this.cursor + 1) % this.value.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.value.length - 1; + } else { + this.cursor--; + } + + this.render(); + } + + down() { + if (this.cursor === this.value.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + + this.render(); + } + + left() { + this.value[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.value[this.cursor].selected = true; + this.render(); + } + + handleSpaceToggle() { + const v = this.value[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + toggleAll() { + if (this.maxChoices !== undefined || this.value[this.cursor].disabled) { + return this.bell(); + } + + const newSelected = !this.value[this.cursor].selected; + this.value.filter(v => !v.disabled).forEach(v => v.selected = newSelected); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else if (c === 'a') { + this.toggleAll(); + } else { + return this.bell(); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + + return '\nInstructions:\n' + ` ${figures.arrowUp}/${figures.arrowDown}: Highlight option\n` + ` ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection\n` + (this.maxChoices === undefined ? ` a: Toggle all\n` : '') + ` enter/return: Complete answer`; + } + + return ''; + } + + renderOption(cursor, v, i, arrowIndicator) { + const prefix = (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' '; + let title, desc; + + if (v.disabled) { + title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + } else { + title = cursor === i ? color.cyan().underline(v.title) : v.title; + + if (cursor === i && v.description) { + desc = ` - ${v.description}`; + + if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { + margin: prefix.length, + width: this.out.columns + }); + } + } + } + + return prefix + title + color.gray(desc || ''); + } // shared with autocompleteMultiselect + + + paginateOptions(options) { + if (options.length === 0) { + return color.red('No matches for this query.'); + } + + let _entriesToDisplay = entriesToDisplay(this.cursor, options.length, this.optionsPerPage), + startIndex = _entriesToDisplay.startIndex, + endIndex = _entriesToDisplay.endIndex; + + let prefix, + styledOptions = []; + + for (let i = startIndex; i < endIndex; i++) { + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < options.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + + styledOptions.push(this.renderOption(this.cursor, options[i], i, prefix)); + } + + return '\n' + styledOptions.join('\n'); + } // shared with autocomleteMultiselect + + + renderOptions(options) { + if (!this.done) { + return this.paginateOptions(options); + } + + return ''; + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value.filter(e => e.selected).map(v => v.title).join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions()]; + + if (this.value[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); // print prompt + + let prompt = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(' '); + + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + + prompt += this.renderOptions(this.value); + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } + + } + + multiselect$1 = MultiselectPrompt; + return multiselect$1; +} + +var autocomplete$1; +var hasRequiredAutocomplete$1; + +function requireAutocomplete$1 () { + if (hasRequiredAutocomplete$1) return autocomplete$1; + hasRequiredAutocomplete$1 = 1; + + 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 color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireSrc(), + erase = _require.erase, + cursor = _require.cursor; + + const _require2 = requireUtil$1(), + style = _require2.style, + clear = _require2.clear, + figures = _require2.figures, + wrap = _require2.wrap, + entriesToDisplay = _require2.entriesToDisplay; + + const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]); + + const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]); + + const getIndex = (arr, valOrTitle) => { + const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle); + return index > -1 ? index : undefined; + }; + /** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of auto-complete choices objects + * @param {Function} [opts.suggest] Filter function. Defaults to sort by title + * @param {Number} [opts.limit=10] Max number of results to show + * @param {Number} [opts.cursor=0] Cursor start position + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.fallback] Fallback message - initial to default value + * @param {String} [opts.initial] Index of the default value + * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.noMatches] The no matches found label + */ + + + class AutocompletePrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.suggest = opts.suggest; + this.choices = opts.choices; + this.initial = typeof opts.initial === 'number' ? opts.initial : getIndex(opts.choices, opts.initial); + this.select = this.initial || opts.cursor || 0; + this.i18n = { + noMatches: opts.noMatches || 'no matches found' + }; + this.fallback = opts.fallback || this.initial; + this.clearFirst = opts.clearFirst || false; + this.suggestions = []; + this.input = ''; + this.limit = opts.limit || 10; + this.cursor = 0; + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.render = this.render.bind(this); + this.complete = this.complete.bind(this); + this.clear = clear('', this.out.columns); + this.complete(this.render); + this.render(); + } + + set fallback(fb) { + this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb; + } + + get fallback() { + let choice; + if (typeof this._fb === 'number') choice = this.choices[this._fb];else if (typeof this._fb === 'string') choice = { + title: this._fb + }; + return choice || this._fb || { + title: this.i18n.noMatches + }; + } + + moveSelect(i) { + this.select = i; + if (this.suggestions.length > 0) this.value = getVal(this.suggestions, i);else this.value = this.fallback.value; + this.fire(); + } + + complete(cb) { + var _this = this; + + return _asyncToGenerator(function* () { + const p = _this.completing = _this.suggest(_this.input, _this.choices); + + const suggestions = yield p; + if (_this.completing !== p) return; + _this.suggestions = suggestions.map((s, i, arr) => ({ + title: getTitle(arr, i), + value: getVal(arr, i), + description: s.description + })); + _this.completing = false; + const l = Math.max(suggestions.length - 1, 0); + + _this.moveSelect(Math.min(l, _this.select)); + + cb && cb(); + })(); + } + + reset() { + this.input = ''; + this.complete(() => { + this.moveSelect(this.initial !== void 0 ? this.initial : 0); + this.render(); + }); + this.render(); + } + + exit() { + if (this.clearFirst && this.input.length > 0) { + this.reset(); + } else { + this.done = this.exited = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + abort() { + this.done = this.aborted = true; + this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${c}${s2}`; + this.cursor = s1.length + 1; + this.complete(this.render); + this.render(); + } + + delete() { + if (this.cursor === 0) return this.bell(); + let s1 = this.input.slice(0, this.cursor - 1); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.cursor = this.cursor - 1; + this.render(); + } + + deleteForward() { + if (this.cursor * this.scale >= this.rendered.length) return this.bell(); + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor + 1); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.render(); + } + + first() { + this.moveSelect(0); + this.render(); + } + + last() { + this.moveSelect(this.suggestions.length - 1); + this.render(); + } + + up() { + if (this.select === 0) { + this.moveSelect(this.suggestions.length - 1); + } else { + this.moveSelect(this.select - 1); + } + + this.render(); + } + + down() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else { + this.moveSelect(this.select + 1); + } + + this.render(); + } + + next() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else this.moveSelect(this.select + 1); + + this.render(); + } + + nextPage() { + this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1)); + this.render(); + } + + prevPage() { + this.moveSelect(Math.max(this.select - this.limit, 0)); + this.render(); + } + + left() { + if (this.cursor <= 0) return this.bell(); + this.cursor = this.cursor - 1; + this.render(); + } + + right() { + if (this.cursor * this.scale >= this.rendered.length) return this.bell(); + this.cursor = this.cursor + 1; + this.render(); + } + + renderOption(v, hovered, isStart, isEnd) { + let desc; + let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : ' '; + let title = hovered ? color.cyan().underline(v.title) : v.title; + prefix = (hovered ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + + if (v.description) { + desc = ` - ${v.description}`; + + if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { + margin: 3, + width: this.out.columns + }); + } + } + + return prefix + ' ' + title + color.gray(desc || ''); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let _entriesToDisplay = entriesToDisplay(this.select, this.choices.length, this.limit), + startIndex = _entriesToDisplay.startIndex, + endIndex = _entriesToDisplay.endIndex; + + this.outputText = [style.symbol(this.done, this.aborted, this.exited), color.bold(this.msg), style.delimiter(this.completing), this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input)].join(' '); + + if (!this.done) { + const suggestions = this.suggestions.slice(startIndex, endIndex).map((item, i) => this.renderOption(item, this.select === i + startIndex, i === 0 && startIndex > 0, i + startIndex === endIndex - 1 && endIndex < this.choices.length)).join('\n'); + this.outputText += `\n` + (suggestions || color.gray(this.fallback.title)); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + + } + + autocomplete$1 = AutocompletePrompt; + return autocomplete$1; +} + +var autocompleteMultiselect$1; +var hasRequiredAutocompleteMultiselect$1; + +function requireAutocompleteMultiselect$1 () { + if (hasRequiredAutocompleteMultiselect$1) return autocompleteMultiselect$1; + hasRequiredAutocompleteMultiselect$1 = 1; + + const color = requireKleur(); + + const _require = requireSrc(), + cursor = _require.cursor; + + const MultiselectPrompt = requireMultiselect$1(); + + const _require2 = requireUtil$1(), + clear = _require2.clear, + style = _require2.style, + figures = _require2.figures; + /** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + + class AutocompleteMultiselectPrompt extends MultiselectPrompt { + constructor(opts = {}) { + opts.overrideRender = true; + super(opts); + this.inputValue = ''; + this.clear = clear('', this.out.columns); + this.filteredOptions = this.value; + this.render(); + } + + last() { + this.cursor = this.filteredOptions.length - 1; + this.render(); + } + + next() { + this.cursor = (this.cursor + 1) % this.filteredOptions.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.filteredOptions.length - 1; + } else { + this.cursor--; + } + + this.render(); + } + + down() { + if (this.cursor === this.filteredOptions.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + + this.render(); + } + + left() { + this.filteredOptions[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.filteredOptions[this.cursor].selected = true; + this.render(); + } + + delete() { + if (this.inputValue.length) { + this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1); + this.updateFilteredOptions(); + } + } + + updateFilteredOptions() { + const currentHighlight = this.filteredOptions[this.cursor]; + this.filteredOptions = this.value.filter(v => { + if (this.inputValue) { + if (typeof v.title === 'string') { + if (v.title.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + + if (typeof v.value === 'string') { + if (v.value.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + + return false; + } + + return true; + }); + const newHighlightIndex = this.filteredOptions.findIndex(v => v === currentHighlight); + this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex; + this.render(); + } + + handleSpaceToggle() { + const v = this.filteredOptions[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + handleInputChange(c) { + this.inputValue = this.inputValue + c; + this.updateFilteredOptions(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else { + this.handleInputChange(c); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + + return ` +Instructions: + ${figures.arrowUp}/${figures.arrowDown}: Highlight option + ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection + [a,b,c]/delete: Filter choices + enter/return: Complete answer +`; + } + + return ''; + } + + renderCurrentInput() { + return ` +Filtered results for: ${this.inputValue ? this.inputValue : color.gray('Enter something to filter')}\n`; + } + + renderOption(cursor, v, i) { + let title; + if (v.disabled) title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title);else title = cursor === i ? color.cyan().underline(v.title) : v.title; + return (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + title; + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value.filter(e => e.selected).map(v => v.title).join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()]; + + if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); // print prompt + + let prompt = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(' '); + + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + + prompt += this.renderOptions(this.filteredOptions); + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } + + } + + autocompleteMultiselect$1 = AutocompleteMultiselectPrompt; + return autocompleteMultiselect$1; +} + +var confirm$1; +var hasRequiredConfirm$1; + +function requireConfirm$1 () { + if (hasRequiredConfirm$1) return confirm$1; + hasRequiredConfirm$1 = 1; + + const color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireUtil$1(), + style = _require.style, + clear = _require.clear; + + const _require2 = requireSrc(), + erase = _require2.erase, + cursor = _require2.cursor; + /** + * ConfirmPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial] Default value (true/false) + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.yes] The "Yes" label + * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no + * @param {String} [opts.no] The "No" label + * @param {String} [opts.noOption] The "No" option when choosing between yes/no + */ + + + class ConfirmPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.value = opts.initial; + this.initialValue = !!opts.initial; + this.yesMsg = opts.yes || 'yes'; + this.yesOption = opts.yesOption || '(Y/n)'; + this.noMsg = opts.no || 'no'; + this.noOption = opts.noOption || '(y/N)'; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.value = this.value || false; + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + if (c.toLowerCase() === 'y') { + this.value = true; + return this.submit(); + } + + if (c.toLowerCase() === 'n') { + this.value = false; + return this.submit(); + } + + return this.bell(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.done ? this.value ? this.yesMsg : this.noMsg : color.gray(this.initialValue ? this.yesOption : this.noOption)].join(' '); + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + + } + + confirm$1 = ConfirmPrompt; + return confirm$1; +} + +var elements$1; +var hasRequiredElements$1; + +function requireElements$1 () { + if (hasRequiredElements$1) return elements$1; + hasRequiredElements$1 = 1; + + elements$1 = { + TextPrompt: requireText$1(), + SelectPrompt: requireSelect$1(), + TogglePrompt: requireToggle$1(), + DatePrompt: requireDate$1(), + NumberPrompt: requireNumber$1(), + MultiselectPrompt: requireMultiselect$1(), + AutocompletePrompt: requireAutocomplete$1(), + AutocompleteMultiselectPrompt: requireAutocompleteMultiselect$1(), + ConfirmPrompt: requireConfirm$1() + }; + return elements$1; +} + +var hasRequiredPrompts$1; + +function requirePrompts$1 () { + if (hasRequiredPrompts$1) return prompts$2; + hasRequiredPrompts$1 = 1; + (function (exports) { + + const $ = exports; + + const el = requireElements$1(); + + const noop = v => v; + + function toPrompt(type, args, opts = {}) { + return new Promise((res, rej) => { + const p = new el[type](args); + const onAbort = opts.onAbort || noop; + const onSubmit = opts.onSubmit || noop; + const onExit = opts.onExit || noop; + p.on('state', args.onState || noop); + p.on('submit', x => res(onSubmit(x))); + p.on('exit', x => res(onExit(x))); + p.on('abort', x => rej(onAbort(x))); + }); + } + /** + * Text prompt + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.text = args => toPrompt('TextPrompt', args); + /** + * Password prompt with masked input + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.password = args => { + args.style = 'password'; + return $.text(args); + }; + /** + * Prompt where input is invisible, like sudo + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.invisible = args => { + args.style = 'invisible'; + return $.text(args); + }; + /** + * Number prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.number = args => toPrompt('NumberPrompt', args); + /** + * Date prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.date = args => toPrompt('DatePrompt', args); + /** + * Classic yes/no prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.confirm = args => toPrompt('ConfirmPrompt', args); + /** + * List prompt, split intput string by `seperator` + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {string} [args.separator] String separator + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input, in form of an `Array` + */ + + + $.list = args => { + const sep = args.separator || ','; + return toPrompt('TextPrompt', args, { + onSubmit: str => str.split(sep).map(s => s.trim()) + }); + }; + /** + * Toggle/switch prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {string} [args.active="on"] Text for `active` state + * @param {string} [args.inactive="off"] Text for `inactive` state + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.toggle = args => toPrompt('TogglePrompt', args); + /** + * Interactive select prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value }, ...]` + * @param {number} [args.initial] Index of default value + * @param {String} [args.hint] Hint to display + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.select = args => toPrompt('SelectPrompt', args); + /** + * Interactive multi-select / autocompleteMultiselect prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value, [selected] }, ...]` + * @param {number} [args.max] Max select + * @param {string} [args.hint] Hint to display user + * @param {Number} [args.cursor=0] Cursor start position + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.multiselect = args => { + args.choices = [].concat(args.choices || []); + + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + + return toPrompt('MultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); + }; + + $.autocompleteMultiselect = args => { + args.choices = [].concat(args.choices || []); + + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + + return toPrompt('AutocompleteMultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); + }; + + const byTitle = (input, choices) => Promise.resolve(choices.filter(item => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase())); + /** + * Interactive auto-complete prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of auto-complete choices objects `[{ title, value }, ...]` + * @param {Function} [args.suggest] Function to filter results based on user input. Defaults to sort by `title` + * @param {number} [args.limit=10] Max number of results to show + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {String} [args.initial] Index of the default value + * @param {boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {String} [args.fallback] Fallback message - defaults to initial value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.autocomplete = args => { + args.suggest = args.suggest || byTitle; + args.choices = [].concat(args.choices || []); + return toPrompt('AutocompletePrompt', args); + }; +} (prompts$2)); + return prompts$2; +} + +var dist; +var hasRequiredDist; + +function requireDist () { + if (hasRequiredDist) return dist; + hasRequiredDist = 1; + + 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; } + + function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + + 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 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 prompts = requirePrompts$1(); + + const passOn = ['suggest', 'format', 'onState', 'validate', 'onRender', 'type']; + + const noop = () => {}; + /** + * Prompt for a series of questions + * @param {Array|Object} questions Single question object or Array of question objects + * @param {Function} [onSubmit] Callback function called on prompt submit + * @param {Function} [onCancel] Callback function called on cancel/abort + * @returns {Object} Object with values from user input + */ + + + function prompt() { + return _prompt.apply(this, arguments); + } + + function _prompt() { + _prompt = _asyncToGenerator(function* (questions = [], { + onSubmit = noop, + onCancel = noop + } = {}) { + const answers = {}; + const override = prompt._override || {}; + questions = [].concat(questions); + let answer, question, quit, name, type, lastPrompt; + + const getFormattedAnswer = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(function* (question, answer, skipValidation = false) { + if (!skipValidation && question.validate && question.validate(answer) !== true) { + return; + } + + return question.format ? yield question.format(answer, answers) : answer; + }); + + return function getFormattedAnswer(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + + var _iterator = _createForOfIteratorHelper(questions), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + question = _step.value; + var _question = question; + name = _question.name; + type = _question.type; + + // evaluate type first and skip if type is a falsy value + if (typeof type === 'function') { + type = yield type(answer, _objectSpread({}, answers), question); + question['type'] = type; + } + + if (!type) continue; // if property is a function, invoke it unless it's a special function + + for (let key in question) { + if (passOn.includes(key)) continue; + let value = question[key]; + question[key] = typeof value === 'function' ? yield value(answer, _objectSpread({}, answers), lastPrompt) : value; + } + + lastPrompt = question; + + if (typeof question.message !== 'string') { + throw new Error('prompt message is required'); + } // update vars in case they changed + + + var _question2 = question; + name = _question2.name; + type = _question2.type; + + if (prompts[type] === void 0) { + throw new Error(`prompt type (${type}) is not defined`); + } + + if (override[question.name] !== undefined) { + answer = yield getFormattedAnswer(question, override[question.name]); + + if (answer !== undefined) { + answers[name] = answer; + continue; + } + } + + try { + // Get the injected answer if there is one or prompt the user + answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : yield prompts[type](question); + answers[name] = answer = yield getFormattedAnswer(question, answer, true); + quit = yield onSubmit(question, answer, answers); + } catch (err) { + quit = !(yield onCancel(question, answers)); + } + + if (quit) return answers; + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return answers; + }); + return _prompt.apply(this, arguments); + } + + function getInjectedAnswer(injected, deafultValue) { + const answer = injected.shift(); + + if (answer instanceof Error) { + throw answer; + } + + return answer === undefined ? deafultValue : answer; + } + + function inject(answers) { + prompt._injected = (prompt._injected || []).concat(answers); + } + + function override(answers) { + prompt._override = Object.assign({}, answers); + } + + dist = Object.assign(prompt, { + prompt, + prompts, + inject, + override + }); + return dist; +} + +var prompts$1 = {}; + +var action; +var hasRequiredAction; + +function requireAction () { + if (hasRequiredAction) return action; + hasRequiredAction = 1; + + action = (key, isSelect) => { + if (key.meta && key.name !== 'escape') return; + + if (key.ctrl) { + if (key.name === 'a') return 'first'; + if (key.name === 'c') return 'abort'; + if (key.name === 'd') return 'abort'; + if (key.name === 'e') return 'last'; + if (key.name === 'g') return 'reset'; + } + + if (isSelect) { + if (key.name === 'j') return 'down'; + if (key.name === 'k') return 'up'; + } + + if (key.name === 'return') return 'submit'; + if (key.name === 'enter') return 'submit'; // ctrl + J + if (key.name === 'backspace') return 'delete'; + if (key.name === 'delete') return 'deleteForward'; + if (key.name === 'abort') return 'abort'; + if (key.name === 'escape') return 'exit'; + if (key.name === 'tab') return 'next'; + if (key.name === 'pagedown') return 'nextPage'; + if (key.name === 'pageup') return 'prevPage'; + // TODO create home() in prompt types (e.g. TextPrompt) + if (key.name === 'home') return 'home'; + // TODO create end() in prompt types (e.g. TextPrompt) + if (key.name === 'end') return 'end'; + + if (key.name === 'up') return 'up'; + if (key.name === 'down') return 'down'; + if (key.name === 'right') return 'right'; + if (key.name === 'left') return 'left'; + + return false; + }; + return action; +} + +var strip; +var hasRequiredStrip; + +function requireStrip () { + if (hasRequiredStrip) return strip; + hasRequiredStrip = 1; + + strip = str => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' + ].join('|'); + + const RGX = new RegExp(pattern, 'g'); + return typeof str === 'string' ? str.replace(RGX, '') : str; + }; + return strip; +} + +var clear; +var hasRequiredClear; + +function requireClear () { + if (hasRequiredClear) return clear; + hasRequiredClear = 1; + + const strip = requireStrip(); + const { erase, cursor } = requireSrc(); + + const width = str => [...strip(str)].length; + + /** + * @param {string} prompt + * @param {number} perLine + */ + clear = function(prompt, perLine) { + if (!perLine) return erase.line + cursor.to(0); + + let rows = 0; + const lines = prompt.split(/\r?\n/); + for (let line of lines) { + rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine); + } + + return erase.lines(rows); + }; + return clear; +} + +var figures_1; +var hasRequiredFigures; + +function requireFigures () { + if (hasRequiredFigures) return figures_1; + hasRequiredFigures = 1; + + const main = { + arrowUp: '↑', + arrowDown: '↓', + arrowLeft: '←', + arrowRight: '→', + radioOn: '◉', + radioOff: '◯', + tick: '✔', + cross: '✖', + ellipsis: '…', + pointerSmall: '›', + line: '─', + pointer: '❯' + }; + const win = { + arrowUp: main.arrowUp, + arrowDown: main.arrowDown, + arrowLeft: main.arrowLeft, + arrowRight: main.arrowRight, + radioOn: '(*)', + radioOff: '( )', + tick: '√', + cross: '×', + ellipsis: '...', + pointerSmall: '»', + line: '─', + pointer: '>' + }; + const figures = process.platform === 'win32' ? win : main; + + figures_1 = figures; + return figures_1; +} + +var style; +var hasRequiredStyle; + +function requireStyle () { + if (hasRequiredStyle) return style; + hasRequiredStyle = 1; + + const c = requireKleur(); + const figures = requireFigures(); + + // rendering user input. + const styles = Object.freeze({ + password: { scale: 1, render: input => '*'.repeat(input.length) }, + emoji: { scale: 2, render: input => '😃'.repeat(input.length) }, + invisible: { scale: 0, render: input => '' }, + default: { scale: 1, render: input => `${input}` } + }); + const render = type => styles[type] || styles.default; + + // icon to signalize a prompt. + const symbols = Object.freeze({ + aborted: c.red(figures.cross), + done: c.green(figures.tick), + exited: c.yellow(figures.cross), + default: c.cyan('?') + }); + + const symbol = (done, aborted, exited) => + aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default; + + // between the question and the user's input. + const delimiter = completing => + c.gray(completing ? figures.ellipsis : figures.pointerSmall); + + const item = (expandable, expanded) => + c.gray(expandable ? (expanded ? figures.pointerSmall : '+') : figures.line); + + style = { + styles, + render, + symbols, + symbol, + delimiter, + item + }; + return style; +} + +var lines; +var hasRequiredLines; + +function requireLines () { + if (hasRequiredLines) return lines; + hasRequiredLines = 1; + + const strip = requireStrip(); + + /** + * @param {string} msg + * @param {number} perLine + */ + lines = function (msg, perLine) { + let lines = String(strip(msg) || '').split(/\r?\n/); + + if (!perLine) return lines.length; + return lines.map(l => Math.ceil(l.length / perLine)) + .reduce((a, b) => a + b); + }; + return lines; +} + +var wrap; +var hasRequiredWrap; + +function requireWrap () { + if (hasRequiredWrap) return wrap; + hasRequiredWrap = 1; + + /** + * @param {string} msg The message to wrap + * @param {object} opts + * @param {number|string} [opts.margin] Left margin + * @param {number} opts.width Maximum characters per line including the margin + */ + wrap = (msg, opts = {}) => { + const tab = Number.isSafeInteger(parseInt(opts.margin)) + ? new Array(parseInt(opts.margin)).fill(' ').join('') + : (opts.margin || ''); + + const width = opts.width; + + return (msg || '').split(/\r?\n/g) + .map(line => line + .split(/\s+/g) + .reduce((arr, w) => { + if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width) + arr[arr.length - 1] += ` ${w}`; + else arr.push(`${tab}${w}`); + return arr; + }, [ tab ]) + .join('\n')) + .join('\n'); + }; + return wrap; +} + +var entriesToDisplay; +var hasRequiredEntriesToDisplay; + +function requireEntriesToDisplay () { + if (hasRequiredEntriesToDisplay) return entriesToDisplay; + hasRequiredEntriesToDisplay = 1; + + /** + * Determine what entries should be displayed on the screen, based on the + * currently selected index and the maximum visible. Used in list-based + * prompts like `select` and `multiselect`. + * + * @param {number} cursor the currently selected entry + * @param {number} total the total entries available to display + * @param {number} [maxVisible] the number of entries that can be displayed + */ + entriesToDisplay = (cursor, total, maxVisible) => { + maxVisible = maxVisible || total; + + let startIndex = Math.min(total- maxVisible, cursor - Math.floor(maxVisible / 2)); + if (startIndex < 0) startIndex = 0; + + let endIndex = Math.min(startIndex + maxVisible, total); + + return { startIndex, endIndex }; + }; + return entriesToDisplay; +} + +var util; +var hasRequiredUtil; + +function requireUtil () { + if (hasRequiredUtil) return util; + hasRequiredUtil = 1; + + util = { + action: requireAction(), + clear: requireClear(), + style: requireStyle(), + strip: requireStrip(), + figures: requireFigures(), + lines: requireLines(), + wrap: requireWrap(), + entriesToDisplay: requireEntriesToDisplay() + }; + return util; +} + +var prompt; +var hasRequiredPrompt; + +function requirePrompt () { + if (hasRequiredPrompt) return prompt; + hasRequiredPrompt = 1; + + const readline = require$$0; + const { action } = requireUtil(); + const EventEmitter = require$$2; + const { beep, cursor } = requireSrc(); + const color = requireKleur(); + + /** + * Base prompt skeleton + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + class Prompt extends EventEmitter { + constructor(opts={}) { + super(); + + this.firstRender = true; + this.in = opts.stdin || process.stdin; + this.out = opts.stdout || process.stdout; + this.onRender = (opts.onRender || (() => void 0)).bind(this); + const rl = readline.createInterface({ input:this.in, escapeCodeTimeout:50 }); + readline.emitKeypressEvents(this.in, rl); + + if (this.in.isTTY) this.in.setRawMode(true); + const isSelect = [ 'SelectPrompt', 'MultiselectPrompt' ].indexOf(this.constructor.name) > -1; + const keypress = (str, key) => { + let a = action(key, isSelect); + if (a === false) { + this._ && this._(str, key); + } else if (typeof this[a] === 'function') { + this[a](key); + } else { + this.bell(); + } + }; + + this.close = () => { + this.out.write(cursor.show); + this.in.removeListener('keypress', keypress); + if (this.in.isTTY) this.in.setRawMode(false); + rl.close(); + this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value); + this.closed = true; + }; + + this.in.on('keypress', keypress); + } + + fire() { + this.emit('state', { + value: this.value, + aborted: !!this.aborted, + exited: !!this.exited + }); + } + + bell() { + this.out.write(beep); + } + + render() { + this.onRender(color); + if (this.firstRender) this.firstRender = false; + } + } + + prompt = Prompt; + return prompt; +} + +var text; +var hasRequiredText; + +function requireText () { + if (hasRequiredText) return text; + hasRequiredText = 1; + const color = requireKleur(); + const Prompt = requirePrompt(); + const { erase, cursor } = requireSrc(); + const { style, clear, lines, figures } = requireUtil(); + + /** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.initial] Default value + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ + class TextPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.msg = opts.message; + this.initial = opts.initial || ``; + this.validator = opts.validate || (() => true); + this.value = ``; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.clear = clear(``, this.out.columns); + this.render(); + } + + set value(v) { + if (!v && this.initial) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(this.initial)); + } else { + this.placeholder = false; + this.rendered = this.transform.render(v); + } + this._value = v; + this.fire(); + } + + get value() { + return this._value; + } + + reset() { + this.value = ``; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.value = this.value || this.initial; + this.done = this.aborted = true; + this.error = false; + this.red = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + async validate() { + let valid = await this.validator(this.value); + if (typeof valid === `string`) { + this.errorMsg = valid; + valid = false; + } + this.error = !valid; + } + + async submit() { + this.value = this.value || this.initial; + this.cursorOffset = 0; + this.cursor = this.rendered.length; + await this.validate(); + if (this.error) { + this.red = true; + this.fire(); + this.render(); + return; + } + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + next() { + if (!this.placeholder) return this.bell(); + this.value = this.initial; + this.cursor = this.rendered.length; + this.fire(); + this.render(); + } + + moveCursor(n) { + if (this.placeholder) return; + this.cursor = this.cursor+n; + this.cursorOffset += n; + } + + _(c, key) { + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${c}${s2}`; + this.red = false; + this.cursor = this.placeholder ? 0 : s1.length+1; + this.render(); + } + + delete() { + if (this.isCursorAtStart()) return this.bell(); + let s1 = this.value.slice(0, this.cursor-1); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${s2}`; + this.red = false; + if (this.isCursorAtStart()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + this.moveCursor(-1); + } + this.render(); + } + + deleteForward() { + if(this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell(); + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor+1); + this.value = `${s1}${s2}`; + this.red = false; + if (this.isCursorAtEnd()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + } + this.render(); + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length; + this.render(); + } + + left() { + if (this.cursor <= 0 || this.placeholder) return this.bell(); + this.moveCursor(-1); + this.render(); + } + + right() { + if (this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell(); + this.moveCursor(1); + this.render(); + } + + isCursorAtStart() { + return this.cursor === 0 || (this.placeholder && this.cursor === 1); + } + + isCursorAtEnd() { + return this.cursor === this.rendered.length || (this.placeholder && this.cursor === this.rendered.length + 1) + } + + render() { + if (this.closed) return; + if (!this.firstRender) { + if (this.outputError) + this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + super.render(); + this.outputError = ''; + + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + this.red ? color.red(this.rendered) : this.rendered + ].join(` `); + + if (this.error) { + this.outputError += this.errorMsg.split(`\n`) + .reduce((a, l, i) => a + `\n${i ? ' ' : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0)); + } + } + + text = TextPrompt; + return text; +} + +var select; +var hasRequiredSelect; + +function requireSelect () { + if (hasRequiredSelect) return select; + hasRequiredSelect = 1; + + const color = requireKleur(); + const Prompt = requirePrompt(); + const { style, clear, figures, wrap, entriesToDisplay } = requireUtil(); + const { cursor } = requireSrc(); + + /** + * SelectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {Number} [opts.initial] Index of default value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + */ + class SelectPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.hint = opts.hint || '- Use arrow-keys. Return to submit.'; + this.warn = opts.warn || '- This option is disabled'; + this.cursor = opts.initial || 0; + this.choices = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') + ch = {title: ch, value: idx}; + return { + title: ch && (ch.title || ch.value || ch), + value: ch && (ch.value === undefined ? idx : ch.value), + description: ch && ch.description, + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = (this.choices[this.cursor] || {}).value; + this.clear = clear('', this.out.columns); + this.render(); + } + + moveCursor(n) { + this.cursor = n; + this.value = this.choices[n].value; + this.fire(); + } + + reset() { + this.moveCursor(0); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + if (!this.selection.disabled) { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } else + this.bell(); + } + + first() { + this.moveCursor(0); + this.render(); + } + + last() { + this.moveCursor(this.choices.length - 1); + this.render(); + } + + up() { + if (this.cursor === 0) { + this.moveCursor(this.choices.length - 1); + } else { + this.moveCursor(this.cursor - 1); + } + this.render(); + } + + down() { + if (this.cursor === this.choices.length - 1) { + this.moveCursor(0); + } else { + this.moveCursor(this.cursor + 1); + } + this.render(); + } + + next() { + this.moveCursor((this.cursor + 1) % this.choices.length); + this.render(); + } + + _(c, key) { + if (c === ' ') return this.submit(); + } + + get selection() { + return this.choices[this.cursor]; + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let { startIndex, endIndex } = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage); + + // Print prompt + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.done ? this.selection.title : this.selection.disabled + ? color.yellow(this.warn) : color.gray(this.hint) + ].join(' '); + + // Print choices + if (!this.done) { + this.outputText += '\n'; + for (let i = startIndex; i < endIndex; i++) { + let title, prefix, desc = '', v = this.choices[i]; + + // Determine whether to display "more choices" indicators + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < this.choices.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + + if (v.disabled) { + title = this.cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + prefix = (this.cursor === i ? color.bold().gray(figures.pointer) + ' ' : ' ') + prefix; + } else { + title = this.cursor === i ? color.cyan().underline(v.title) : v.title; + prefix = (this.cursor === i ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + if (v.description && this.cursor === i) { + desc = ` - ${v.description}`; + if (prefix.length + title.length + desc.length >= this.out.columns + || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns }); + } + } + } + + this.outputText += `${prefix} ${title}${color.gray(desc)}\n`; + } + } + + this.out.write(this.outputText); + } + } + + select = SelectPrompt; + return select; +} + +var toggle; +var hasRequiredToggle; + +function requireToggle () { + if (hasRequiredToggle) return toggle; + hasRequiredToggle = 1; + const color = requireKleur(); + const Prompt = requirePrompt(); + const { style, clear } = requireUtil(); + const { cursor, erase } = requireSrc(); + + /** + * TogglePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial=false] Default value + * @param {String} [opts.active='no'] Active label + * @param {String} [opts.inactive='off'] Inactive label + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + class TogglePrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.value = !!opts.initial; + this.active = opts.active || 'on'; + this.inactive = opts.inactive || 'off'; + this.initialValue = this.value; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + deactivate() { + if (this.value === false) return this.bell(); + this.value = false; + this.render(); + } + + activate() { + if (this.value === true) return this.bell(); + this.value = true; + this.render(); + } + + delete() { + this.deactivate(); + } + left() { + this.deactivate(); + } + right() { + this.activate(); + } + down() { + this.deactivate(); + } + up() { + this.activate(); + } + + next() { + this.value = !this.value; + this.fire(); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.value = !this.value; + } else if (c === '1') { + this.value = true; + } else if (c === '0') { + this.value = false; + } else return this.bell(); + this.render(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + this.value ? this.inactive : color.cyan().underline(this.inactive), + color.gray('/'), + this.value ? color.cyan().underline(this.active) : this.active + ].join(' '); + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + } + + toggle = TogglePrompt; + return toggle; +} + +var datepart; +var hasRequiredDatepart; + +function requireDatepart () { + if (hasRequiredDatepart) return datepart; + hasRequiredDatepart = 1; + + class DatePart { + constructor({token, date, parts, locales}) { + this.token = token; + this.date = date || new Date(); + this.parts = parts || [this]; + this.locales = locales || {}; + } + + up() {} + + down() {} + + next() { + const currentIdx = this.parts.indexOf(this); + return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + setTo(val) {} + + prev() { + let parts = [].concat(this.parts).reverse(); + const currentIdx = parts.indexOf(this); + return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + toString() { + return String(this.date); + } + } + + datepart = DatePart; + return datepart; +} + +var meridiem; +var hasRequiredMeridiem; + +function requireMeridiem () { + if (hasRequiredMeridiem) return meridiem; + hasRequiredMeridiem = 1; + + const DatePart = requireDatepart(); + + class Meridiem extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setHours((this.date.getHours() + 12) % 24); + } + + down() { + this.up(); + } + + toString() { + let meridiem = this.date.getHours() > 12 ? 'pm' : 'am'; + return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem; + } + } + + meridiem = Meridiem; + return meridiem; +} + +var day; +var hasRequiredDay; + +function requireDay () { + if (hasRequiredDay) return day; + hasRequiredDay = 1; + + const DatePart = requireDatepart(); + + const pos = n => { + n = n % 10; + return n === 1 ? 'st' + : n === 2 ? 'nd' + : n === 3 ? 'rd' + : 'th'; + }; + + class Day extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setDate(this.date.getDate() + 1); + } + + down() { + this.date.setDate(this.date.getDate() - 1); + } + + setTo(val) { + this.date.setDate(parseInt(val.substr(-2))); + } + + toString() { + let date = this.date.getDate(); + let day = this.date.getDay(); + return this.token === 'DD' ? String(date).padStart(2, '0') + : this.token === 'Do' ? date + pos(date) + : this.token === 'd' ? day + 1 + : this.token === 'ddd' ? this.locales.weekdaysShort[day] + : this.token === 'dddd' ? this.locales.weekdays[day] + : date; + } + } + + day = Day; + return day; +} + +var hours; +var hasRequiredHours; + +function requireHours () { + if (hasRequiredHours) return hours; + hasRequiredHours = 1; + + const DatePart = requireDatepart(); + + class Hours extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setHours(this.date.getHours() + 1); + } + + down() { + this.date.setHours(this.date.getHours() - 1); + } + + setTo(val) { + this.date.setHours(parseInt(val.substr(-2))); + } + + toString() { + let hours = this.date.getHours(); + if (/h/.test(this.token)) + hours = (hours % 12) || 12; + return this.token.length > 1 ? String(hours).padStart(2, '0') : hours; + } + } + + hours = Hours; + return hours; +} + +var milliseconds; +var hasRequiredMilliseconds; + +function requireMilliseconds () { + if (hasRequiredMilliseconds) return milliseconds; + hasRequiredMilliseconds = 1; + + const DatePart = requireDatepart(); + + class Milliseconds extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setMilliseconds(this.date.getMilliseconds() + 1); + } + + down() { + this.date.setMilliseconds(this.date.getMilliseconds() - 1); + } + + setTo(val) { + this.date.setMilliseconds(parseInt(val.substr(-(this.token.length)))); + } + + toString() { + return String(this.date.getMilliseconds()).padStart(4, '0') + .substr(0, this.token.length); + } + } + + milliseconds = Milliseconds; + return milliseconds; +} + +var minutes; +var hasRequiredMinutes; + +function requireMinutes () { + if (hasRequiredMinutes) return minutes; + hasRequiredMinutes = 1; + + const DatePart = requireDatepart(); + + class Minutes extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setMinutes(this.date.getMinutes() + 1); + } + + down() { + this.date.setMinutes(this.date.getMinutes() - 1); + } + + setTo(val) { + this.date.setMinutes(parseInt(val.substr(-2))); + } + + toString() { + let m = this.date.getMinutes(); + return this.token.length > 1 ? String(m).padStart(2, '0') : m; + } + } + + minutes = Minutes; + return minutes; +} + +var month; +var hasRequiredMonth; + +function requireMonth () { + if (hasRequiredMonth) return month; + hasRequiredMonth = 1; + + const DatePart = requireDatepart(); + + class Month extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setMonth(this.date.getMonth() + 1); + } + + down() { + this.date.setMonth(this.date.getMonth() - 1); + } + + setTo(val) { + val = parseInt(val.substr(-2)) - 1; + this.date.setMonth(val < 0 ? 0 : val); + } + + toString() { + let month = this.date.getMonth(); + let tl = this.token.length; + return tl === 2 ? String(month + 1).padStart(2, '0') + : tl === 3 ? this.locales.monthsShort[month] + : tl === 4 ? this.locales.months[month] + : String(month + 1); + } + } + + month = Month; + return month; +} + +var seconds; +var hasRequiredSeconds; + +function requireSeconds () { + if (hasRequiredSeconds) return seconds; + hasRequiredSeconds = 1; + + const DatePart = requireDatepart(); + + class Seconds extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setSeconds(this.date.getSeconds() + 1); + } + + down() { + this.date.setSeconds(this.date.getSeconds() - 1); + } + + setTo(val) { + this.date.setSeconds(parseInt(val.substr(-2))); + } + + toString() { + let s = this.date.getSeconds(); + return this.token.length > 1 ? String(s).padStart(2, '0') : s; + } + } + + seconds = Seconds; + return seconds; +} + +var year; +var hasRequiredYear; + +function requireYear () { + if (hasRequiredYear) return year; + hasRequiredYear = 1; + + const DatePart = requireDatepart(); + + class Year extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setFullYear(this.date.getFullYear() + 1); + } + + down() { + this.date.setFullYear(this.date.getFullYear() - 1); + } + + setTo(val) { + this.date.setFullYear(val.substr(-4)); + } + + toString() { + let year = String(this.date.getFullYear()).padStart(4, '0'); + return this.token.length === 2 ? year.substr(-2) : year; + } + } + + year = Year; + return year; +} + +var dateparts; +var hasRequiredDateparts; + +function requireDateparts () { + if (hasRequiredDateparts) return dateparts; + hasRequiredDateparts = 1; + + dateparts = { + DatePart: requireDatepart(), + Meridiem: requireMeridiem(), + Day: requireDay(), + Hours: requireHours(), + Milliseconds: requireMilliseconds(), + Minutes: requireMinutes(), + Month: requireMonth(), + Seconds: requireSeconds(), + Year: requireYear(), + }; + return dateparts; +} + +var date; +var hasRequiredDate; + +function requireDate () { + if (hasRequiredDate) return date; + hasRequiredDate = 1; + + const color = requireKleur(); + const Prompt = requirePrompt(); + const { style, clear, figures } = requireUtil(); + const { erase, cursor } = requireSrc(); + const { DatePart, Meridiem, Day, Hours, Milliseconds, Minutes, Month, Seconds, Year } = requireDateparts(); + + const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g; + const regexGroups = { + 1: ({token}) => token.replace(/\\(.)/g, '$1'), + 2: (opts) => new Day(opts), // Day // TODO + 3: (opts) => new Month(opts), // Month + 4: (opts) => new Year(opts), // Year + 5: (opts) => new Meridiem(opts), // AM/PM // TODO (special) + 6: (opts) => new Hours(opts), // Hours + 7: (opts) => new Minutes(opts), // Minutes + 8: (opts) => new Seconds(opts), // Seconds + 9: (opts) => new Milliseconds(opts), // Fractional seconds + }; + + const dfltLocales = { + months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','), + monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), + weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), + weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',') + }; + + + /** + * DatePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Number} [opts.initial] Index of default value + * @param {String} [opts.mask] The format mask + * @param {object} [opts.locales] The date locales + * @param {String} [opts.error] The error message shown on invalid value + * @param {Function} [opts.validate] Function to validate the submitted value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + class DatePrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.cursor = 0; + this.typed = ''; + this.locales = Object.assign(dfltLocales, opts.locales); + this._date = opts.initial || new Date(); + this.errorMsg = opts.error || 'Please Enter A Valid Value'; + this.validator = opts.validate || (() => true); + this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss'; + this.clear = clear('', this.out.columns); + this.render(); + } + + get value() { + return this.date + } + + get date() { + return this._date; + } + + set date(date) { + if (date) this._date.setTime(date.getTime()); + } + + set mask(mask) { + let result; + this.parts = []; + while(result = regex.exec(mask)) { + let match = result.shift(); + let idx = result.findIndex(gr => gr != null); + this.parts.push(idx in regexGroups + ? regexGroups[idx]({ token: result[idx] || match, date: this.date, parts: this.parts, locales: this.locales }) + : result[idx] || match); + } + + let parts = this.parts.reduce((arr, i) => { + if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') + arr[arr.length - 1] += i; + else arr.push(i); + return arr; + }, []); + + this.parts.splice(0); + this.parts.push(...parts); + this.reset(); + } + + moveCursor(n) { + this.typed = ''; + this.cursor = n; + this.fire(); + } + + reset() { + this.moveCursor(this.parts.findIndex(p => p instanceof DatePart)); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + async validate() { + let valid = await this.validator(this.value); + if (typeof valid === 'string') { + this.errorMsg = valid; + valid = false; + } + this.error = !valid; + } + + async submit() { + await this.validate(); + if (this.error) { + this.color = 'red'; + this.fire(); + this.render(); + return; + } + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + up() { + this.typed = ''; + this.parts[this.cursor].up(); + this.render(); + } + + down() { + this.typed = ''; + this.parts[this.cursor].down(); + this.render(); + } + + left() { + let prev = this.parts[this.cursor].prev(); + if (prev == null) return this.bell(); + this.moveCursor(this.parts.indexOf(prev)); + this.render(); + } + + right() { + let next = this.parts[this.cursor].next(); + if (next == null) return this.bell(); + this.moveCursor(this.parts.indexOf(next)); + this.render(); + } + + next() { + let next = this.parts[this.cursor].next(); + this.moveCursor(next + ? this.parts.indexOf(next) + : this.parts.findIndex((part) => part instanceof DatePart)); + this.render(); + } + + _(c) { + if (/\d/.test(c)) { + this.typed += c; + this.parts[this.cursor].setTo(this.typed); + this.render(); + } + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + // Print prompt + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), []) + .join('') + ].join(' '); + + // Print error + if (this.error) { + this.outputText += this.errorMsg.split('\n').reduce( + (a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + } + + date = DatePrompt; + return date; +} + +var number; +var hasRequiredNumber; + +function requireNumber () { + if (hasRequiredNumber) return number; + hasRequiredNumber = 1; + const color = requireKleur(); + const Prompt = requirePrompt(); + const { cursor, erase } = requireSrc(); + const { style, figures, clear, lines } = requireUtil(); + + const isNumber = /[0-9]/; + const isDef = any => any !== undefined; + const round = (number, precision) => { + let factor = Math.pow(10, precision); + return Math.round(number * factor) / factor; + }; + + /** + * NumberPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {Number} [opts.initial] Default value + * @param {Number} [opts.max=+Infinity] Max value + * @param {Number} [opts.min=-Infinity] Min value + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ + class NumberPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.transform = style.render(opts.style); + this.msg = opts.message; + this.initial = isDef(opts.initial) ? opts.initial : ''; + this.float = !!opts.float; + this.round = opts.round || 2; + this.inc = opts.increment || 1; + this.min = isDef(opts.min) ? opts.min : -Infinity; + this.max = isDef(opts.max) ? opts.max : Infinity; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + this.validator = opts.validate || (() => true); + this.color = `cyan`; + this.value = ``; + this.typed = ``; + this.lastHit = 0; + this.render(); + } + + set value(v) { + if (!v && v !== 0) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(`${this.initial}`)); + this._value = ``; + } else { + this.placeholder = false; + this.rendered = this.transform.render(`${round(v, this.round)}`); + this._value = round(v, this.round); + } + this.fire(); + } + + get value() { + return this._value; + } + + parse(x) { + return this.float ? parseFloat(x) : parseInt(x); + } + + valid(c) { + return c === `-` || c === `.` && this.float || isNumber.test(c) + } + + reset() { + this.typed = ``; + this.value = ``; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + let x = this.value; + this.value = x !== `` ? x : this.initial; + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write(`\n`); + this.close(); + } + + async validate() { + let valid = await this.validator(this.value); + if (typeof valid === `string`) { + this.errorMsg = valid; + valid = false; + } + this.error = !valid; + } + + async submit() { + await this.validate(); + if (this.error) { + this.color = `red`; + this.fire(); + this.render(); + return; + } + let x = this.value; + this.value = x !== `` ? x : this.initial; + this.done = true; + this.aborted = false; + this.error = false; + this.fire(); + this.render(); + this.out.write(`\n`); + this.close(); + } + + up() { + this.typed = ``; + if(this.value === '') { + this.value = this.min - this.inc; + } + if (this.value >= this.max) return this.bell(); + this.value += this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + down() { + this.typed = ``; + if(this.value === '') { + this.value = this.min + this.inc; + } + if (this.value <= this.min) return this.bell(); + this.value -= this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + delete() { + let val = this.value.toString(); + if (val.length === 0) return this.bell(); + this.value = this.parse((val = val.slice(0, -1))) || ``; + if (this.value !== '' && this.value < this.min) { + this.value = this.min; + } + this.color = `cyan`; + this.fire(); + this.render(); + } + + next() { + this.value = this.initial; + this.fire(); + this.render(); + } + + _(c, key) { + if (!this.valid(c)) return this.bell(); + + const now = Date.now(); + if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed + this.typed += c; + this.lastHit = now; + this.color = `cyan`; + + if (c === `.`) return this.fire(); + + this.value = Math.min(this.parse(this.typed), this.max); + if (this.value > this.max) this.value = this.max; + if (this.value < this.min) this.value = this.min; + this.fire(); + this.render(); + } + + render() { + if (this.closed) return; + if (!this.firstRender) { + if (this.outputError) + this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + super.render(); + this.outputError = ''; + + // Print prompt + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + !this.done || (!this.done && !this.placeholder) + ? color[this.color]().underline(this.rendered) : this.rendered + ].join(` `); + + // Print error + if (this.error) { + this.outputError += this.errorMsg.split(`\n`) + .reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore); + } + } + + number = NumberPrompt; + return number; +} + +var multiselect; +var hasRequiredMultiselect; + +function requireMultiselect () { + if (hasRequiredMultiselect) return multiselect; + hasRequiredMultiselect = 1; + + const color = requireKleur(); + const { cursor } = requireSrc(); + const Prompt = requirePrompt(); + const { clear, figures, style, wrap, entriesToDisplay } = requireUtil(); + + /** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + class MultiselectPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.cursor = opts.cursor || 0; + this.scrollIndex = opts.cursor || 0; + this.hint = opts.hint || ''; + this.warn = opts.warn || '- This option is disabled -'; + this.minSelected = opts.min; + this.showMinError = false; + this.maxChoices = opts.max; + this.instructions = opts.instructions; + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') + ch = {title: ch, value: idx}; + return { + title: ch && (ch.title || ch.value || ch), + description: ch && ch.description, + value: ch && (ch.value === undefined ? idx : ch.value), + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.clear = clear('', this.out.columns); + if (!opts.overrideRender) { + this.render(); + } + } + + reset() { + this.value.map(v => !v.selected); + this.cursor = 0; + this.fire(); + this.render(); + } + + selected() { + return this.value.filter(v => v.selected); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + const selected = this.value + .filter(e => e.selected); + if (this.minSelected && selected.length < this.minSelected) { + this.showMinError = true; + this.render(); + } else { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length - 1; + this.render(); + } + next() { + this.cursor = (this.cursor + 1) % this.value.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.value.length - 1; + } else { + this.cursor--; + } + this.render(); + } + + down() { + if (this.cursor === this.value.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + this.render(); + } + + left() { + this.value[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.value[this.cursor].selected = true; + this.render(); + } + + handleSpaceToggle() { + const v = this.value[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + toggleAll() { + if (this.maxChoices !== undefined || this.value[this.cursor].disabled) { + return this.bell(); + } + + const newSelected = !this.value[this.cursor].selected; + this.value.filter(v => !v.disabled).forEach(v => v.selected = newSelected); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else if (c === 'a') { + this.toggleAll(); + } else { + return this.bell(); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + return '\nInstructions:\n' + + ` ${figures.arrowUp}/${figures.arrowDown}: Highlight option\n` + + ` ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection\n` + + (this.maxChoices === undefined ? ` a: Toggle all\n` : '') + + ` enter/return: Complete answer`; + } + return ''; + } + + renderOption(cursor, v, i, arrowIndicator) { + const prefix = (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' '; + let title, desc; + + if (v.disabled) { + title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + } else { + title = cursor === i ? color.cyan().underline(v.title) : v.title; + if (cursor === i && v.description) { + desc = ` - ${v.description}`; + if (prefix.length + title.length + desc.length >= this.out.columns + || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { margin: prefix.length, width: this.out.columns }); + } + } + } + + return prefix + title + color.gray(desc || ''); + } + + // shared with autocompleteMultiselect + paginateOptions(options) { + if (options.length === 0) { + return color.red('No matches for this query.'); + } + + let { startIndex, endIndex } = entriesToDisplay(this.cursor, options.length, this.optionsPerPage); + let prefix, styledOptions = []; + + for (let i = startIndex; i < endIndex; i++) { + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < options.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + styledOptions.push(this.renderOption(this.cursor, options[i], i, prefix)); + } + + return '\n' + styledOptions.join('\n'); + } + + // shared with autocomleteMultiselect + renderOptions(options) { + if (!this.done) { + return this.paginateOptions(options); + } + return ''; + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value + .filter(e => e.selected) + .map(v => v.title) + .join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions()]; + + if (this.value[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); + + // print prompt + let prompt = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.renderDoneOrInstructions() + ].join(' '); + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + prompt += this.renderOptions(this.value); + + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } + } + + multiselect = MultiselectPrompt; + return multiselect; +} + +var autocomplete; +var hasRequiredAutocomplete; + +function requireAutocomplete () { + if (hasRequiredAutocomplete) return autocomplete; + hasRequiredAutocomplete = 1; + + const color = requireKleur(); + const Prompt = requirePrompt(); + const { erase, cursor } = requireSrc(); + const { style, clear, figures, wrap, entriesToDisplay } = requireUtil(); + + const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]); + const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]); + const getIndex = (arr, valOrTitle) => { + const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle); + return index > -1 ? index : undefined; + }; + + /** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of auto-complete choices objects + * @param {Function} [opts.suggest] Filter function. Defaults to sort by title + * @param {Number} [opts.limit=10] Max number of results to show + * @param {Number} [opts.cursor=0] Cursor start position + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.fallback] Fallback message - initial to default value + * @param {String} [opts.initial] Index of the default value + * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.noMatches] The no matches found label + */ + class AutocompletePrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.suggest = opts.suggest; + this.choices = opts.choices; + this.initial = typeof opts.initial === 'number' + ? opts.initial + : getIndex(opts.choices, opts.initial); + this.select = this.initial || opts.cursor || 0; + this.i18n = { noMatches: opts.noMatches || 'no matches found' }; + this.fallback = opts.fallback || this.initial; + this.clearFirst = opts.clearFirst || false; + this.suggestions = []; + this.input = ''; + this.limit = opts.limit || 10; + this.cursor = 0; + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.render = this.render.bind(this); + this.complete = this.complete.bind(this); + this.clear = clear('', this.out.columns); + this.complete(this.render); + this.render(); + } + + set fallback(fb) { + this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb; + } + + get fallback() { + let choice; + if (typeof this._fb === 'number') + choice = this.choices[this._fb]; + else if (typeof this._fb === 'string') + choice = { title: this._fb }; + return choice || this._fb || { title: this.i18n.noMatches }; + } + + moveSelect(i) { + this.select = i; + if (this.suggestions.length > 0) + this.value = getVal(this.suggestions, i); + else this.value = this.fallback.value; + this.fire(); + } + + async complete(cb) { + const p = (this.completing = this.suggest(this.input, this.choices)); + const suggestions = await p; + + if (this.completing !== p) return; + this.suggestions = suggestions + .map((s, i, arr) => ({ title: getTitle(arr, i), value: getVal(arr, i), description: s.description })); + this.completing = false; + const l = Math.max(suggestions.length - 1, 0); + this.moveSelect(Math.min(l, this.select)); + + cb && cb(); + } + + reset() { + this.input = ''; + this.complete(() => { + this.moveSelect(this.initial !== void 0 ? this.initial : 0); + this.render(); + }); + this.render(); + } + + exit() { + if (this.clearFirst && this.input.length > 0) { + this.reset(); + } else { + this.done = this.exited = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + abort() { + this.done = this.aborted = true; + this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${c}${s2}`; + this.cursor = s1.length+1; + this.complete(this.render); + this.render(); + } + + delete() { + if (this.cursor === 0) return this.bell(); + let s1 = this.input.slice(0, this.cursor-1); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.cursor = this.cursor-1; + this.render(); + } + + deleteForward() { + if(this.cursor*this.scale >= this.rendered.length) return this.bell(); + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor+1); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.render(); + } + + first() { + this.moveSelect(0); + this.render(); + } + + last() { + this.moveSelect(this.suggestions.length - 1); + this.render(); + } + + up() { + if (this.select === 0) { + this.moveSelect(this.suggestions.length - 1); + } else { + this.moveSelect(this.select - 1); + } + this.render(); + } + + down() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else { + this.moveSelect(this.select + 1); + } + this.render(); + } + + next() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else this.moveSelect(this.select + 1); + this.render(); + } + + nextPage() { + this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1)); + this.render(); + } + + prevPage() { + this.moveSelect(Math.max(this.select - this.limit, 0)); + this.render(); + } + + left() { + if (this.cursor <= 0) return this.bell(); + this.cursor = this.cursor-1; + this.render(); + } + + right() { + if (this.cursor*this.scale >= this.rendered.length) return this.bell(); + this.cursor = this.cursor+1; + this.render(); + } + + renderOption(v, hovered, isStart, isEnd) { + let desc; + let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : ' '; + let title = hovered ? color.cyan().underline(v.title) : v.title; + prefix = (hovered ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + if (v.description) { + desc = ` - ${v.description}`; + if (prefix.length + title.length + desc.length >= this.out.columns + || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns }); + } + } + return prefix + ' ' + title + color.gray(desc || ''); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let { startIndex, endIndex } = entriesToDisplay(this.select, this.choices.length, this.limit); + + this.outputText = [ + style.symbol(this.done, this.aborted, this.exited), + color.bold(this.msg), + style.delimiter(this.completing), + this.done && this.suggestions[this.select] + ? this.suggestions[this.select].title + : this.rendered = this.transform.render(this.input) + ].join(' '); + + if (!this.done) { + const suggestions = this.suggestions + .slice(startIndex, endIndex) + .map((item, i) => this.renderOption(item, + this.select === i + startIndex, + i === 0 && startIndex > 0, + i + startIndex === endIndex - 1 && endIndex < this.choices.length)) + .join('\n'); + this.outputText += `\n` + (suggestions || color.gray(this.fallback.title)); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + } + + autocomplete = AutocompletePrompt; + return autocomplete; +} + +var autocompleteMultiselect; +var hasRequiredAutocompleteMultiselect; + +function requireAutocompleteMultiselect () { + if (hasRequiredAutocompleteMultiselect) return autocompleteMultiselect; + hasRequiredAutocompleteMultiselect = 1; + + const color = requireKleur(); + const { cursor } = requireSrc(); + const MultiselectPrompt = requireMultiselect(); + const { clear, style, figures } = requireUtil(); + /** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + class AutocompleteMultiselectPrompt extends MultiselectPrompt { + constructor(opts={}) { + opts.overrideRender = true; + super(opts); + this.inputValue = ''; + this.clear = clear('', this.out.columns); + this.filteredOptions = this.value; + this.render(); + } + + last() { + this.cursor = this.filteredOptions.length - 1; + this.render(); + } + next() { + this.cursor = (this.cursor + 1) % this.filteredOptions.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.filteredOptions.length - 1; + } else { + this.cursor--; + } + this.render(); + } + + down() { + if (this.cursor === this.filteredOptions.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + this.render(); + } + + left() { + this.filteredOptions[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.filteredOptions[this.cursor].selected = true; + this.render(); + } + + delete() { + if (this.inputValue.length) { + this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1); + this.updateFilteredOptions(); + } + } + + updateFilteredOptions() { + const currentHighlight = this.filteredOptions[this.cursor]; + this.filteredOptions = this.value + .filter(v => { + if (this.inputValue) { + if (typeof v.title === 'string') { + if (v.title.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + if (typeof v.value === 'string') { + if (v.value.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + return false; + } + return true; + }); + const newHighlightIndex = this.filteredOptions.findIndex(v => v === currentHighlight); + this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex; + this.render(); + } + + handleSpaceToggle() { + const v = this.filteredOptions[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + handleInputChange(c) { + this.inputValue = this.inputValue + c; + this.updateFilteredOptions(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else { + this.handleInputChange(c); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + return ` +Instructions: + ${figures.arrowUp}/${figures.arrowDown}: Highlight option + ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection + [a,b,c]/delete: Filter choices + enter/return: Complete answer +`; + } + return ''; + } + + renderCurrentInput() { + return ` +Filtered results for: ${this.inputValue ? this.inputValue : color.gray('Enter something to filter')}\n`; + } + + renderOption(cursor, v, i) { + let title; + if (v.disabled) title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + else title = cursor === i ? color.cyan().underline(v.title) : v.title; + return (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + title + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value + .filter(e => e.selected) + .map(v => v.title) + .join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()]; + + if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); + + // print prompt + + let prompt = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.renderDoneOrInstructions() + ].join(' '); + + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + prompt += this.renderOptions(this.filteredOptions); + + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } + } + + autocompleteMultiselect = AutocompleteMultiselectPrompt; + return autocompleteMultiselect; +} + +var confirm; +var hasRequiredConfirm; + +function requireConfirm () { + if (hasRequiredConfirm) return confirm; + hasRequiredConfirm = 1; + const color = requireKleur(); + const Prompt = requirePrompt(); + const { style, clear } = requireUtil(); + const { erase, cursor } = requireSrc(); + + /** + * ConfirmPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial] Default value (true/false) + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.yes] The "Yes" label + * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no + * @param {String} [opts.no] The "No" label + * @param {String} [opts.noOption] The "No" option when choosing between yes/no + */ + class ConfirmPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.value = opts.initial; + this.initialValue = !!opts.initial; + this.yesMsg = opts.yes || 'yes'; + this.yesOption = opts.yesOption || '(Y/n)'; + this.noMsg = opts.no || 'no'; + this.noOption = opts.noOption || '(y/N)'; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.value = this.value || false; + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + if (c.toLowerCase() === 'y') { + this.value = true; + return this.submit(); + } + if (c.toLowerCase() === 'n') { + this.value = false; + return this.submit(); + } + return this.bell(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + this.done ? (this.value ? this.yesMsg : this.noMsg) + : color.gray(this.initialValue ? this.yesOption : this.noOption) + ].join(' '); + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + } + + confirm = ConfirmPrompt; + return confirm; +} + +var elements; +var hasRequiredElements; + +function requireElements () { + if (hasRequiredElements) return elements; + hasRequiredElements = 1; + + elements = { + TextPrompt: requireText(), + SelectPrompt: requireSelect(), + TogglePrompt: requireToggle(), + DatePrompt: requireDate(), + NumberPrompt: requireNumber(), + MultiselectPrompt: requireMultiselect(), + AutocompletePrompt: requireAutocomplete(), + AutocompleteMultiselectPrompt: requireAutocompleteMultiselect(), + ConfirmPrompt: requireConfirm() + }; + return elements; +} + +var hasRequiredPrompts; + +function requirePrompts () { + if (hasRequiredPrompts) return prompts$1; + hasRequiredPrompts = 1; + (function (exports) { + const $ = exports; + const el = requireElements(); + const noop = v => v; + + function toPrompt(type, args, opts={}) { + return new Promise((res, rej) => { + const p = new el[type](args); + const onAbort = opts.onAbort || noop; + const onSubmit = opts.onSubmit || noop; + const onExit = opts.onExit || noop; + p.on('state', args.onState || noop); + p.on('submit', x => res(onSubmit(x))); + p.on('exit', x => res(onExit(x))); + p.on('abort', x => rej(onAbort(x))); + }); + } + + /** + * Text prompt + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.text = args => toPrompt('TextPrompt', args); + + /** + * Password prompt with masked input + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.password = args => { + args.style = 'password'; + return $.text(args); + }; + + /** + * Prompt where input is invisible, like sudo + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.invisible = args => { + args.style = 'invisible'; + return $.text(args); + }; + + /** + * Number prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.number = args => toPrompt('NumberPrompt', args); + + /** + * Date prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.date = args => toPrompt('DatePrompt', args); + + /** + * Classic yes/no prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.confirm = args => toPrompt('ConfirmPrompt', args); + + /** + * List prompt, split intput string by `seperator` + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {string} [args.separator] String separator + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input, in form of an `Array` + */ + $.list = args => { + const sep = args.separator || ','; + return toPrompt('TextPrompt', args, { + onSubmit: str => str.split(sep).map(s => s.trim()) + }); + }; + + /** + * Toggle/switch prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {string} [args.active="on"] Text for `active` state + * @param {string} [args.inactive="off"] Text for `inactive` state + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.toggle = args => toPrompt('TogglePrompt', args); + + /** + * Interactive select prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value }, ...]` + * @param {number} [args.initial] Index of default value + * @param {String} [args.hint] Hint to display + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.select = args => toPrompt('SelectPrompt', args); + + /** + * Interactive multi-select / autocompleteMultiselect prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value, [selected] }, ...]` + * @param {number} [args.max] Max select + * @param {string} [args.hint] Hint to display user + * @param {Number} [args.cursor=0] Cursor start position + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.multiselect = args => { + args.choices = [].concat(args.choices || []); + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + return toPrompt('MultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); + }; + + $.autocompleteMultiselect = args => { + args.choices = [].concat(args.choices || []); + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + return toPrompt('AutocompleteMultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); + }; + + const byTitle = (input, choices) => Promise.resolve( + choices.filter(item => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase()) + ); + + /** + * Interactive auto-complete prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of auto-complete choices objects `[{ title, value }, ...]` + * @param {Function} [args.suggest] Function to filter results based on user input. Defaults to sort by `title` + * @param {number} [args.limit=10] Max number of results to show + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {String} [args.initial] Index of the default value + * @param {boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {String} [args.fallback] Fallback message - defaults to initial value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.autocomplete = args => { + args.suggest = args.suggest || byTitle; + args.choices = [].concat(args.choices || []); + return toPrompt('AutocompletePrompt', args); + }; +} (prompts$1)); + return prompts$1; +} + +var lib; +var hasRequiredLib; + +function requireLib () { + if (hasRequiredLib) return lib; + hasRequiredLib = 1; + + const prompts = requirePrompts(); + + const passOn = ['suggest', 'format', 'onState', 'validate', 'onRender', 'type']; + const noop = () => {}; + + /** + * Prompt for a series of questions + * @param {Array|Object} questions Single question object or Array of question objects + * @param {Function} [onSubmit] Callback function called on prompt submit + * @param {Function} [onCancel] Callback function called on cancel/abort + * @returns {Object} Object with values from user input + */ + async function prompt(questions=[], { onSubmit=noop, onCancel=noop }={}) { + const answers = {}; + const override = prompt._override || {}; + questions = [].concat(questions); + let answer, question, quit, name, type, lastPrompt; + + const getFormattedAnswer = async (question, answer, skipValidation = false) => { + if (!skipValidation && question.validate && question.validate(answer) !== true) { + return; + } + return question.format ? await question.format(answer, answers) : answer + }; + + for (question of questions) { + ({ name, type } = question); + + // evaluate type first and skip if type is a falsy value + if (typeof type === 'function') { + type = await type(answer, { ...answers }, question); + question['type'] = type; + } + if (!type) continue; + + // if property is a function, invoke it unless it's a special function + for (let key in question) { + if (passOn.includes(key)) continue; + let value = question[key]; + question[key] = typeof value === 'function' ? await value(answer, { ...answers }, lastPrompt) : value; + } + + lastPrompt = question; + + if (typeof question.message !== 'string') { + throw new Error('prompt message is required'); + } + + // update vars in case they changed + ({ name, type } = question); + + if (prompts[type] === void 0) { + throw new Error(`prompt type (${type}) is not defined`); + } + + if (override[question.name] !== undefined) { + answer = await getFormattedAnswer(question, override[question.name]); + if (answer !== undefined) { + answers[name] = answer; + continue; + } + } + + try { + // Get the injected answer if there is one or prompt the user + answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : await prompts[type](question); + answers[name] = answer = await getFormattedAnswer(question, answer, true); + quit = await onSubmit(question, answer, answers); + } catch (err) { + quit = !(await onCancel(question, answers)); + } + + if (quit) return answers; + } + + return answers; + } + + function getInjectedAnswer(injected, deafultValue) { + const answer = injected.shift(); + if (answer instanceof Error) { + throw answer; + } + + return (answer === undefined) ? deafultValue : answer; + } + + function inject(answers) { + prompt._injected = (prompt._injected || []).concat(answers); + } + + function override(answers) { + prompt._override = Object.assign({}, answers); + } + + lib = Object.assign(prompt, { prompt, prompts, inject, override }); + return lib; +} + +function isNodeLT(tar) { + tar = (Array.isArray(tar) ? tar : tar.split('.')).map(Number); + let i=0, src=process.versions.node.split('.').map(Number); + for (; i < tar.length; i++) { + if (src[i] > tar[i]) return false; + if (tar[i] > src[i]) return true; + } + return false; +} + +var prompts = + isNodeLT('8.6.0') + ? requireDist() + : requireLib(); + +var index = /*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': prompts +}, [prompts]); + +export { index as i, prompts as p }; diff --git a/node_modules/vitest/dist/vendor-index.b2fdde54.js b/node_modules/vitest/dist/vendor-index.b2fdde54.js new file mode 100644 index 0000000..c8b8b36 --- /dev/null +++ b/node_modules/vitest/dist/vendor-index.b2fdde54.js @@ -0,0 +1,1071 @@ +import { Buffer } from 'node:buffer'; +import path from 'node:path'; +import childProcess from 'node:child_process'; +import process$1 from 'node:process'; +import { s as signalExit, m as mergeStream, g as getStream, c as crossSpawn } from './vendor-index.7a2cebfe.js'; +import url from 'node:url'; +import { constants } from 'os'; +import os from 'node:os'; + +function stripFinalNewline(input) { + const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); + const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); + + if (input[input.length - 1] === LF) { + input = input.slice(0, -1); + } + + if (input[input.length - 1] === CR) { + input = input.slice(0, -1); + } + + return input; +} + +function pathKey(options = {}) { + const { + env = process.env, + platform = process.platform + } = options; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(env).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +} + +function npmRunPath(options = {}) { + const { + cwd = process$1.cwd(), + path: path_ = process$1.env[pathKey()], + execPath = process$1.execPath, + } = options; + + let previous; + const cwdString = cwd instanceof URL ? url.fileURLToPath(cwd) : cwd; + let cwdPath = path.resolve(cwdString); + const result = []; + + while (previous !== cwdPath) { + result.push(path.join(cwdPath, 'node_modules/.bin')); + previous = cwdPath; + cwdPath = path.resolve(cwdPath, '..'); + } + + // Ensure the running `node` binary is used. + result.push(path.resolve(cwdString, execPath, '..')); + + return [...result, path_].join(path.delimiter); +} + +function npmRunPathEnv({env = process$1.env, ...options} = {}) { + env = {...env}; + + const path = pathKey({env}); + options.path = env[path]; + env[path] = npmRunPath(options); + + return env; +} + +const copyProperty = (to, from, property, ignoreNonConfigurable) => { + // `Function#length` should reflect the parameters of `to` not `from` since we keep its body. + // `Function#prototype` is non-writable and non-configurable so can never be modified. + if (property === 'length' || property === 'prototype') { + return; + } + + // `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here. + if (property === 'arguments' || property === 'caller') { + return; + } + + const toDescriptor = Object.getOwnPropertyDescriptor(to, property); + const fromDescriptor = Object.getOwnPropertyDescriptor(from, property); + + if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) { + return; + } + + Object.defineProperty(to, property, fromDescriptor); +}; + +// `Object.defineProperty()` throws if the property exists, is not configurable and either: +// - one its descriptors is changed +// - it is non-writable and its value is changed +const canCopyProperty = function (toDescriptor, fromDescriptor) { + return toDescriptor === undefined || toDescriptor.configurable || ( + toDescriptor.writable === fromDescriptor.writable && + toDescriptor.enumerable === fromDescriptor.enumerable && + toDescriptor.configurable === fromDescriptor.configurable && + (toDescriptor.writable || toDescriptor.value === fromDescriptor.value) + ); +}; + +const changePrototype = (to, from) => { + const fromPrototype = Object.getPrototypeOf(from); + if (fromPrototype === Object.getPrototypeOf(to)) { + return; + } + + Object.setPrototypeOf(to, fromPrototype); +}; + +const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`; + +const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString'); +const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); + +// We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected. +// We use `bind()` instead of a closure for the same reason. +// Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times. +const changeToString = (to, from, name) => { + const withName = name === '' ? '' : `with ${name.trim()}() `; + const newToString = wrappedToString.bind(null, withName, from.toString()); + // Ensure `to.toString.toString` is non-enumerable and has the same `same` + Object.defineProperty(newToString, 'name', toStringName); + Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString}); +}; + +function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) { + const {name} = to; + + for (const property of Reflect.ownKeys(from)) { + copyProperty(to, from, property, ignoreNonConfigurable); + } + + changePrototype(to, from); + changeToString(to, from, name); + + return to; +} + +const calledFunctions = new WeakMap(); + +const onetime = (function_, options = {}) => { + if (typeof function_ !== 'function') { + throw new TypeError('Expected a function'); + } + + let returnValue; + let callCount = 0; + const functionName = function_.displayName || function_.name || ''; + + const onetime = function (...arguments_) { + calledFunctions.set(onetime, ++callCount); + + if (callCount === 1) { + returnValue = function_.apply(this, arguments_); + function_ = null; + } else if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } + + return returnValue; + }; + + mimicFunction(onetime, function_); + calledFunctions.set(onetime, callCount); + + return onetime; +}; + +onetime.callCount = function_ => { + if (!calledFunctions.has(function_)) { + throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); + } + + return calledFunctions.get(function_); +}; + +const getRealtimeSignals=function(){ +const length=SIGRTMAX-SIGRTMIN+1; +return Array.from({length},getRealtimeSignal); +}; + +const getRealtimeSignal=function(value,index){ +return { +name:`SIGRT${index+1}`, +number:SIGRTMIN+index, +action:"terminate", +description:"Application-specific signal (realtime)", +standard:"posix"}; + +}; + +const SIGRTMIN=34; +const SIGRTMAX=64; + +const SIGNALS=[ +{ +name:"SIGHUP", +number:1, +action:"terminate", +description:"Terminal closed", +standard:"posix"}, + +{ +name:"SIGINT", +number:2, +action:"terminate", +description:"User interruption with CTRL-C", +standard:"ansi"}, + +{ +name:"SIGQUIT", +number:3, +action:"core", +description:"User interruption with CTRL-\\", +standard:"posix"}, + +{ +name:"SIGILL", +number:4, +action:"core", +description:"Invalid machine instruction", +standard:"ansi"}, + +{ +name:"SIGTRAP", +number:5, +action:"core", +description:"Debugger breakpoint", +standard:"posix"}, + +{ +name:"SIGABRT", +number:6, +action:"core", +description:"Aborted", +standard:"ansi"}, + +{ +name:"SIGIOT", +number:6, +action:"core", +description:"Aborted", +standard:"bsd"}, + +{ +name:"SIGBUS", +number:7, +action:"core", +description: +"Bus error due to misaligned, non-existing address or paging error", +standard:"bsd"}, + +{ +name:"SIGEMT", +number:7, +action:"terminate", +description:"Command should be emulated but is not implemented", +standard:"other"}, + +{ +name:"SIGFPE", +number:8, +action:"core", +description:"Floating point arithmetic error", +standard:"ansi"}, + +{ +name:"SIGKILL", +number:9, +action:"terminate", +description:"Forced termination", +standard:"posix", +forced:true}, + +{ +name:"SIGUSR1", +number:10, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, + +{ +name:"SIGSEGV", +number:11, +action:"core", +description:"Segmentation fault", +standard:"ansi"}, + +{ +name:"SIGUSR2", +number:12, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, + +{ +name:"SIGPIPE", +number:13, +action:"terminate", +description:"Broken pipe or socket", +standard:"posix"}, + +{ +name:"SIGALRM", +number:14, +action:"terminate", +description:"Timeout or timer", +standard:"posix"}, + +{ +name:"SIGTERM", +number:15, +action:"terminate", +description:"Termination", +standard:"ansi"}, + +{ +name:"SIGSTKFLT", +number:16, +action:"terminate", +description:"Stack is empty or overflowed", +standard:"other"}, + +{ +name:"SIGCHLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"posix"}, + +{ +name:"SIGCLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"other"}, + +{ +name:"SIGCONT", +number:18, +action:"unpause", +description:"Unpaused", +standard:"posix", +forced:true}, + +{ +name:"SIGSTOP", +number:19, +action:"pause", +description:"Paused", +standard:"posix", +forced:true}, + +{ +name:"SIGTSTP", +number:20, +action:"pause", +description:"Paused using CTRL-Z or \"suspend\"", +standard:"posix"}, + +{ +name:"SIGTTIN", +number:21, +action:"pause", +description:"Background process cannot read terminal input", +standard:"posix"}, + +{ +name:"SIGBREAK", +number:21, +action:"terminate", +description:"User interruption with CTRL-BREAK", +standard:"other"}, + +{ +name:"SIGTTOU", +number:22, +action:"pause", +description:"Background process cannot write to terminal output", +standard:"posix"}, + +{ +name:"SIGURG", +number:23, +action:"ignore", +description:"Socket received out-of-band data", +standard:"bsd"}, + +{ +name:"SIGXCPU", +number:24, +action:"core", +description:"Process timed out", +standard:"bsd"}, + +{ +name:"SIGXFSZ", +number:25, +action:"core", +description:"File too big", +standard:"bsd"}, + +{ +name:"SIGVTALRM", +number:26, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, + +{ +name:"SIGPROF", +number:27, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, + +{ +name:"SIGWINCH", +number:28, +action:"ignore", +description:"Terminal window size changed", +standard:"bsd"}, + +{ +name:"SIGIO", +number:29, +action:"terminate", +description:"I/O is available", +standard:"other"}, + +{ +name:"SIGPOLL", +number:29, +action:"terminate", +description:"Watched event", +standard:"other"}, + +{ +name:"SIGINFO", +number:29, +action:"ignore", +description:"Request for process information", +standard:"other"}, + +{ +name:"SIGPWR", +number:30, +action:"terminate", +description:"Device running out of power", +standard:"systemv"}, + +{ +name:"SIGSYS", +number:31, +action:"core", +description:"Invalid system call", +standard:"other"}, + +{ +name:"SIGUNUSED", +number:31, +action:"terminate", +description:"Invalid system call", +standard:"other"}]; + +const getSignals=function(){ +const realtimeSignals=getRealtimeSignals(); +const signals=[...SIGNALS,...realtimeSignals].map(normalizeSignal); +return signals; +}; + + + + + + + +const normalizeSignal=function({ +name, +number:defaultNumber, +description, +action, +forced=false, +standard}) +{ +const{ +signals:{[name]:constantSignal}}= +constants; +const supported=constantSignal!==undefined; +const number=supported?constantSignal:defaultNumber; +return {name,number,description,supported,action,forced,standard}; +}; + +const getSignalsByName=function(){ +const signals=getSignals(); +return signals.reduce(getSignalByName,{}); +}; + +const getSignalByName=function( +signalByNameMemo, +{name,number,description,supported,action,forced,standard}) +{ +return { +...signalByNameMemo, +[name]:{name,number,description,supported,action,forced,standard}}; + +}; + +const signalsByName=getSignalsByName(); + + + + +const getSignalsByNumber=function(){ +const signals=getSignals(); +const length=SIGRTMAX+1; +const signalsA=Array.from({length},(value,number)=> +getSignalByNumber(number,signals)); + +return Object.assign({},...signalsA); +}; + +const getSignalByNumber=function(number,signals){ +const signal=findSignalByNumber(number,signals); + +if(signal===undefined){ +return {}; +} + +const{name,description,supported,action,forced,standard}=signal; +return { +[number]:{ +name, +number, +description, +supported, +action, +forced, +standard}}; + + +}; + + + +const findSignalByNumber=function(number,signals){ +const signal=signals.find(({name})=>constants.signals[name]===number); + +if(signal!==undefined){ +return signal; +} + +return signals.find((signalA)=>signalA.number===number); +}; + +getSignalsByNumber(); + +const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { + if (timedOut) { + return `timed out after ${timeout} milliseconds`; + } + + if (isCanceled) { + return 'was canceled'; + } + + if (errorCode !== undefined) { + return `failed with ${errorCode}`; + } + + if (signal !== undefined) { + return `was killed with ${signal} (${signalDescription})`; + } + + if (exitCode !== undefined) { + return `failed with exit code ${exitCode}`; + } + + return 'failed'; +}; + +const makeError = ({ + stdout, + stderr, + all, + error, + signal, + exitCode, + command, + escapedCommand, + timedOut, + isCanceled, + killed, + parsed: {options: {timeout}}, +}) => { + // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. + // We normalize them to `undefined` + exitCode = exitCode === null ? undefined : exitCode; + signal = signal === null ? undefined : signal; + const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; + + const errorCode = error && error.code; + + const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); + const execaMessage = `Command ${prefix}: ${command}`; + const isError = Object.prototype.toString.call(error) === '[object Error]'; + const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; + const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); + + if (isError) { + error.originalMessage = error.message; + error.message = message; + } else { + error = new Error(message); + } + + error.shortMessage = shortMessage; + error.command = command; + error.escapedCommand = escapedCommand; + error.exitCode = exitCode; + error.signal = signal; + error.signalDescription = signalDescription; + error.stdout = stdout; + error.stderr = stderr; + + if (all !== undefined) { + error.all = all; + } + + if ('bufferedData' in error) { + delete error.bufferedData; + } + + error.failed = true; + error.timedOut = Boolean(timedOut); + error.isCanceled = isCanceled; + error.killed = killed && !timedOut; + + return error; +}; + +const aliases = ['stdin', 'stdout', 'stderr']; + +const hasAlias = options => aliases.some(alias => options[alias] !== undefined); + +const normalizeStdio = options => { + if (!options) { + return; + } + + const {stdio} = options; + + if (stdio === undefined) { + return aliases.map(alias => options[alias]); + } + + if (hasAlias(options)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); + } + + if (typeof stdio === 'string') { + return stdio; + } + + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } + + const length = Math.max(stdio.length, aliases.length); + return Array.from({length}, (value, index) => stdio[index]); +}; + +const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; + +// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior +const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => { + const killResult = kill(signal); + setKillTimeout(kill, signal, options, killResult); + return killResult; +}; + +const setKillTimeout = (kill, signal, options, killResult) => { + if (!shouldForceKill(signal, options, killResult)) { + return; + } + + const timeout = getForceKillAfterTimeout(options); + const t = setTimeout(() => { + kill('SIGKILL'); + }, timeout); + + // Guarded because there's no `.unref()` when `execa` is used in the renderer + // process in Electron. This cannot be tested since we don't run tests in + // Electron. + // istanbul ignore else + if (t.unref) { + t.unref(); + } +}; + +const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult; + +const isSigterm = signal => signal === os.constants.signals.SIGTERM + || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); + +const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { + if (forceKillAfterTimeout === true) { + return DEFAULT_FORCE_KILL_TIMEOUT; + } + + if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { + throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); + } + + return forceKillAfterTimeout; +}; + +// `childProcess.cancel()` +const spawnedCancel = (spawned, context) => { + const killResult = spawned.kill(); + + if (killResult) { + context.isCanceled = true; + } +}; + +const timeoutKill = (spawned, signal, reject) => { + spawned.kill(signal); + reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); +}; + +// `timeout` option handling +const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { + if (timeout === 0 || timeout === undefined) { + return spawnedPromise; + } + + let timeoutId; + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + timeoutKill(spawned, killSignal, reject); + }, timeout); + }); + + const safeSpawnedPromise = spawnedPromise.finally(() => { + clearTimeout(timeoutId); + }); + + return Promise.race([timeoutPromise, safeSpawnedPromise]); +}; + +const validateTimeout = ({timeout}) => { + if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { + throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); + } +}; + +// `cleanup` option handling +const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => { + if (!cleanup || detached) { + return timedPromise; + } + + const removeExitHandler = signalExit.exports(() => { + spawned.kill(); + }); + + return timedPromise.finally(() => { + removeExitHandler(); + }); +}; + +function isStream(stream) { + return stream !== null + && typeof stream === 'object' + && typeof stream.pipe === 'function'; +} + +// `input` option +const handleInput = (spawned, input) => { + // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 + // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 + if (input === undefined || spawned.stdin === undefined) { + return; + } + + if (isStream(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } +}; + +// `all` interleaves `stdout` and `stderr` +const makeAllStream = (spawned, {all}) => { + if (!all || (!spawned.stdout && !spawned.stderr)) { + return; + } + + const mixed = mergeStream(); + + if (spawned.stdout) { + mixed.add(spawned.stdout); + } + + if (spawned.stderr) { + mixed.add(spawned.stderr); + } + + return mixed; +}; + +// On failure, `result.stdout|stderr|all` should contain the currently buffered stream +const getBufferedData = async (stream, streamPromise) => { + if (!stream) { + return; + } + + stream.destroy(); + + try { + return await streamPromise; + } catch (error) { + return error.bufferedData; + } +}; + +const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { + if (!stream || !buffer) { + return; + } + + if (encoding) { + return getStream.exports(stream, {encoding, maxBuffer}); + } + + return getStream.exports.buffer(stream, {maxBuffer}); +}; + +// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) +const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { + const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); + const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); + const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); + + try { + return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); + } catch (error) { + return Promise.all([ + {error, signal: error.signal, timedOut: error.timedOut}, + getBufferedData(stdout, stdoutPromise), + getBufferedData(stderr, stderrPromise), + getBufferedData(all, allPromise), + ]); + } +}; + +const nativePromisePrototype = (async () => {})().constructor.prototype; +const descriptors = ['then', 'catch', 'finally'].map(property => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property), +]); + +// The return value is a mixin of `childProcess` and `Promise` +const mergePromise = (spawned, promise) => { + for (const [property, descriptor] of descriptors) { + // Starting the main `promise` is deferred to avoid consuming streams + const value = typeof promise === 'function' + ? (...args) => Reflect.apply(descriptor.value, promise(), args) + : descriptor.value.bind(promise); + + Reflect.defineProperty(spawned, property, {...descriptor, value}); + } + + return spawned; +}; + +// Use promises instead of `child_process` events +const getSpawnedPromise = spawned => new Promise((resolve, reject) => { + spawned.on('exit', (exitCode, signal) => { + resolve({exitCode, signal}); + }); + + spawned.on('error', error => { + reject(error); + }); + + if (spawned.stdin) { + spawned.stdin.on('error', error => { + reject(error); + }); + } +}); + +const normalizeArgs = (file, args = []) => { + if (!Array.isArray(args)) { + return [file]; + } + + return [file, ...args]; +}; + +const NO_ESCAPE_REGEXP = /^[\w.-]+$/; +const DOUBLE_QUOTES_REGEXP = /"/g; + +const escapeArg = arg => { + if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) { + return arg; + } + + return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`; +}; + +const joinCommand = (file, args) => normalizeArgs(file, args).join(' '); + +const getEscapedCommand = (file, args) => normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' '); + +const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; + +const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { + const env = extendEnv ? {...process$1.env, ...envOption} : envOption; + + if (preferLocal) { + return npmRunPathEnv({env, cwd: localDir, execPath}); + } + + return env; +}; + +const handleArguments = (file, args, options = {}) => { + const parsed = crossSpawn.exports._parse(file, args, options); + file = parsed.command; + args = parsed.args; + options = parsed.options; + + options = { + maxBuffer: DEFAULT_MAX_BUFFER, + buffer: true, + stripFinalNewline: true, + extendEnv: true, + preferLocal: false, + localDir: options.cwd || process$1.cwd(), + execPath: process$1.execPath, + encoding: 'utf8', + reject: true, + cleanup: true, + all: false, + windowsHide: true, + ...options, + }; + + options.env = getEnv(options); + + options.stdio = normalizeStdio(options); + + if (process$1.platform === 'win32' && path.basename(file, '.exe') === 'cmd') { + // #116 + args.unshift('/q'); + } + + return {file, args, options, parsed}; +}; + +const handleOutput = (options, value, error) => { + if (typeof value !== 'string' && !Buffer.isBuffer(value)) { + // When `execaSync()` errors, we normalize it to '' to mimic `execa()` + return error === undefined ? undefined : ''; + } + + if (options.stripFinalNewline) { + return stripFinalNewline(value); + } + + return value; +}; + +function execa(file, args, options) { + const parsed = handleArguments(file, args, options); + const command = joinCommand(file, args); + const escapedCommand = getEscapedCommand(file, args); + + validateTimeout(parsed.options); + + let spawned; + try { + spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options); + } catch (error) { + // Ensure the returned error is always both a promise and a child process + const dummySpawned = new childProcess.ChildProcess(); + const errorPromise = Promise.reject(makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + escapedCommand, + parsed, + timedOut: false, + isCanceled: false, + killed: false, + })); + return mergePromise(dummySpawned, errorPromise); + } + + const spawnedPromise = getSpawnedPromise(spawned); + const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); + const processDone = setExitHandler(spawned, parsed.options, timedPromise); + + const context = {isCanceled: false}; + + spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); + spawned.cancel = spawnedCancel.bind(null, spawned, context); + + const handlePromise = async () => { + const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); + const stdout = handleOutput(parsed.options, stdoutResult); + const stderr = handleOutput(parsed.options, stderrResult); + const all = handleOutput(parsed.options, allResult); + + if (error || exitCode !== 0 || signal !== null) { + const returnedError = makeError({ + error, + exitCode, + signal, + stdout, + stderr, + all, + command, + escapedCommand, + parsed, + timedOut, + isCanceled: context.isCanceled || (parsed.options.signal ? parsed.options.signal.aborted : false), + killed: spawned.killed, + }); + + if (!parsed.options.reject) { + return returnedError; + } + + throw returnedError; + } + + return { + command, + escapedCommand, + exitCode: 0, + stdout, + stderr, + all, + failed: false, + timedOut: false, + isCanceled: false, + killed: false, + }; + }; + + const handlePromiseOnce = onetime(handlePromise); + + handleInput(spawned, parsed.options.input); + + spawned.all = makeAllStream(spawned, parsed.options); + + return mergePromise(spawned, handlePromiseOnce); +} + +export { execa as e }; diff --git a/node_modules/vitest/dist/worker.js b/node_modules/vitest/dist/worker.js new file mode 100644 index 0000000..44a02b8 --- /dev/null +++ b/node_modules/vitest/dist/worker.js @@ -0,0 +1,104 @@ +import { b as resolve, f as distDir } from './chunk-utils-env.b861e3a0.js'; +import { c as createBirpc } from './vendor-index.783e7f3e.js'; +import { workerId } from 'tinypool'; +import { ModuleCacheMap } from 'vite-node/client'; +import { g as getWorkerState } from './chunk-mock-date.a1c85759.js'; +import { e as executeInViteNode } from './chunk-runtime-mocker.a677dd28.js'; +import { r as rpc } from './chunk-runtime-rpc.7f83c8a9.js'; +import { p as processError } from './chunk-runtime-error.fad2c32b.js'; +import 'node:url'; +import 'path'; +import 'node:path'; +import 'picocolors'; +import 'local-pkg'; +import 'vite-node/utils'; +import 'vite'; +import './vendor-index.2e96c50b.js'; +import 'acorn'; +import 'node:module'; +import 'node:fs'; +import 'url'; +import 'fs'; +import 'module'; +import 'assert'; +import 'util'; +import './chunk-utils-timers.52534f96.js'; +import 'chai'; + +let _viteNode; +const moduleCache = new ModuleCacheMap(); +const mockMap = /* @__PURE__ */ new Map(); +async function startViteNode(ctx) { + if (_viteNode) + return _viteNode; + const processExit = process.exit; + process.on("beforeExit", (code) => { + rpc().onWorkerExit(code); + }); + process.exit = (code = process.exitCode || 0) => { + rpc().onWorkerExit(code); + return processExit(code); + }; + process.on("unhandledRejection", (err) => { + rpc().onUnhandledRejection(processError(err)); + }); + const { config } = ctx; + const { run: run2 } = (await executeInViteNode({ + files: [ + resolve(distDir, "entry.js") + ], + fetchModule(id) { + return rpc().fetch(id); + }, + resolveId(id, importer) { + return rpc().resolveId(id, importer); + }, + moduleCache, + mockMap, + interopDefault: config.deps.interopDefault, + root: config.root, + base: config.base + }))[0]; + _viteNode = { run: run2 }; + return _viteNode; +} +function init(ctx) { + if (typeof __vitest_worker__ !== "undefined" && ctx.config.threads && ctx.config.isolate) + throw new Error(`worker for ${ctx.files.join(",")} already initialized by ${getWorkerState().ctx.files.join(",")}. This is probably an internal bug of Vitest.`); + const { config, port, workerId: workerId$1 } = ctx; + process.env.VITEST_WORKER_ID = String(workerId$1); + process.env.VITEST_POOL_ID = String(workerId); + globalThis.__vitest_environment__ = config.environment; + globalThis.__vitest_worker__ = { + ctx, + moduleCache, + config, + mockMap, + rpc: createBirpc( + {}, + { + eventNames: ["onUserConsoleLog", "onFinished", "onCollected", "onWorkerExit"], + post(v) { + port.postMessage(v); + }, + on(fn) { + port.addListener("message", fn); + } + } + ) + }; + if (ctx.invalidates) { + ctx.invalidates.forEach((fsPath) => { + moduleCache.delete(fsPath); + moduleCache.delete(`mock:${fsPath}`); + }); + } + ctx.files.forEach((i) => moduleCache.delete(i)); +} +async function run(ctx) { + init(ctx); + const { run: run2 } = await startViteNode(ctx); + return run2(ctx.files, ctx.config); +} + +export { run }; diff --git a/node_modules/vitest/environments.d.ts b/node_modules/vitest/environments.d.ts new file mode 100644 index 0000000..9758d6e --- /dev/null +++ b/node_modules/vitest/environments.d.ts @@ -0,0 +1 @@ +export * from './dist/environments' diff --git a/node_modules/vitest/globals.d.ts b/node_modules/vitest/globals.d.ts new file mode 100644 index 0000000..c1096c5 --- /dev/null +++ b/node_modules/vitest/globals.d.ts @@ -0,0 +1,17 @@ +declare global { + const suite: typeof import('vitest')['suite'] + const test: typeof import('vitest')['test'] + const describe: typeof import('vitest')['describe'] + const it: typeof import('vitest')['it'] + const expectTypeOf: typeof import('vitest')['expectTypeOf'] + const assertType: typeof import('vitest')['assertType'] + const expect: typeof import('vitest')['expect'] + const assert: typeof import('vitest')['assert'] + const vitest: typeof import('vitest')['vitest'] + const vi: typeof import('vitest')['vitest'] + const beforeAll: typeof import('vitest')['beforeAll'] + const afterAll: typeof import('vitest')['afterAll'] + const beforeEach: typeof import('vitest')['beforeEach'] + const afterEach: typeof import('vitest')['afterEach'] +} +export {} diff --git a/node_modules/vitest/importMeta.d.ts b/node_modules/vitest/importMeta.d.ts new file mode 100644 index 0000000..6892126 --- /dev/null +++ b/node_modules/vitest/importMeta.d.ts @@ -0,0 +1,4 @@ +interface ImportMeta { + url: string + readonly vitest?: typeof import('vitest') +} diff --git a/node_modules/vitest/index.cjs b/node_modules/vitest/index.cjs new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/vitest/index.d.cts b/node_modules/vitest/index.d.cts new file mode 100644 index 0000000..09e9c9b --- /dev/null +++ b/node_modules/vitest/index.d.cts @@ -0,0 +1 @@ +export * from './dist/index.js' diff --git a/node_modules/vitest/node.d.ts b/node_modules/vitest/node.d.ts new file mode 100644 index 0000000..18975f6 --- /dev/null +++ b/node_modules/vitest/node.d.ts @@ -0,0 +1 @@ +export * from './dist/node.js' diff --git a/node_modules/vitest/package.json b/node_modules/vitest/package.json new file mode 100644 index 0000000..6f28028 --- /dev/null +++ b/node_modules/vitest/package.json @@ -0,0 +1,168 @@ +{ + "name": "vitest", + "type": "module", + "version": "0.27.0", + "description": "A blazing fast unit test framework powered by Vite", + "author": "Anthony Fu ", + "license": "MIT", + "funding": "https://github.com/sponsors/antfu", + "homepage": "https://github.com/vitest-dev/vitest#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/vitest" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vite", + "vite-node", + "vitest", + "test", + "jest" + ], + "sideEffects": false, + "exports": { + ".": { + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + }, + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "./*": "./*", + "./globals": { + "types": "./globals.d.ts" + }, + "./importMeta": { + "types": "./importMeta.d.ts" + }, + "./node": { + "types": "./dist/node.d.ts", + "import": "./dist/node.js" + }, + "./environments": { + "types": "./dist/environments.d.ts", + "import": "./dist/environments.js" + }, + "./browser": { + "types": "./dist/browser.d.ts", + "import": "./dist/browser.js" + }, + "./config": { + "types": "./config.d.ts", + "require": "./dist/config.cjs", + "import": "./dist/config.js" + } + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "bin": { + "vitest": "./vitest.mjs" + }, + "files": [ + "dist", + "bin", + "*.d.ts", + "*.d.cts", + "*.mjs", + "*.cjs" + ], + "engines": { + "node": ">=v14.16.0" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@vitest/browser": "*", + "@vitest/ui": "*", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@vitest/ui": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "@edge-runtime/vm": { + "optional": true + } + }, + "dependencies": { + "@types/chai": "^4.3.4", + "@types/chai-subset": "^1.3.3", + "@types/node": "*", + "acorn": "^8.8.1", + "acorn-walk": "^8.2.0", + "cac": "^6.7.14", + "chai": "^4.3.7", + "debug": "^4.3.4", + "local-pkg": "^0.4.2", + "picocolors": "^1.0.0", + "source-map": "^0.6.1", + "strip-literal": "^1.0.0", + "tinybench": "^2.3.1", + "tinypool": "^0.3.0", + "tinyspy": "^1.0.2", + "vite": "^3.0.0 || ^4.0.0", + "vite-node": "0.27.0" + }, + "devDependencies": { + "@antfu/install-pkg": "^0.1.1", + "@edge-runtime/vm": "2.0.2", + "@sinonjs/fake-timers": "^10.0.2", + "@types/diff": "^5.0.2", + "@types/jsdom": "^20.0.1", + "@types/micromatch": "^4.0.2", + "@types/natural-compare": "^1.4.1", + "@types/prompts": "^2.4.2", + "@types/sinonjs__fake-timers": "^8.1.2", + "birpc": "^0.2.3", + "chai-subset": "^1.6.0", + "cli-truncate": "^3.1.0", + "diff": "^5.1.0", + "event-target-polyfill": "^0.0.3", + "execa": "^6.1.0", + "expect-type": "^0.15.0", + "fast-glob": "^3.2.12", + "find-up": "^6.3.0", + "flatted": "^3.2.7", + "get-tsconfig": "^4.2.0", + "happy-dom": "^7.8.1", + "jsdom": "^20.0.3", + "log-update": "^5.0.1", + "magic-string": "^0.27.0", + "micromatch": "^4.0.5", + "mlly": "^1.0.0", + "natural-compare": "^1.4.0", + "p-limit": "^4.0.0", + "pathe": "^0.2.0", + "pkg-types": "^1.0.1", + "pretty-format": "^27.5.1", + "prompts": "^2.4.2", + "rollup": "^2.79.1", + "strip-ansi": "^7.0.1", + "typescript": "^4.9.4", + "ws": "^8.11.0", + "@vitest/expect": "0.27.0", + "@vitest/utils": "0.27.0", + "@vitest/spy": "0.27.0", + "@vitest/ui": "0.27.0" + }, + "scripts": { + "build": "rimraf dist && rollup -c", + "dev": "NODE_OPTIONS=\"--max-old-space-size=8192\" rollup -c --watch -m inline" + } +} \ No newline at end of file diff --git a/node_modules/vitest/suppress-warnings.cjs b/node_modules/vitest/suppress-warnings.cjs new file mode 100644 index 0000000..b4fb718 --- /dev/null +++ b/node_modules/vitest/suppress-warnings.cjs @@ -0,0 +1,20 @@ +// borrowed from tsx implementation: +// https://github.com/esbuild-kit/tsx + +const ignoreWarnings = new Set([ + '--experimental-loader is an experimental feature. This feature could change at any time', + 'Custom ESM Loaders is an experimental feature. This feature could change at any time', +]) + +const { emit } = process + +process.emit = function (event, warning) { + if ( + event === 'warning' + && ignoreWarnings.has(warning.message) + ) + return + + // eslint-disable-next-line prefer-rest-params + return Reflect.apply(emit, this, arguments) +} diff --git a/node_modules/vitest/vitest.mjs b/node_modules/vitest/vitest.mjs new file mode 100755 index 0000000..b4de875 --- /dev/null +++ b/node_modules/vitest/vitest.mjs @@ -0,0 +1,2 @@ +#!/usr/bin/env node +import './dist/cli-wrapper.js' diff --git a/node_modules/which-boxed-primitive/.editorconfig b/node_modules/which-boxed-primitive/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/node_modules/which-boxed-primitive/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/which-boxed-primitive/.eslintignore b/node_modules/which-boxed-primitive/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/which-boxed-primitive/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/which-boxed-primitive/.eslintrc b/node_modules/which-boxed-primitive/.eslintrc new file mode 100644 index 0000000..bfa96d1 --- /dev/null +++ b/node_modules/which-boxed-primitive/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements": [2, 12], + }, +} diff --git a/node_modules/which-boxed-primitive/.github/FUNDING.yml b/node_modules/which-boxed-primitive/.github/FUNDING.yml new file mode 100644 index 0000000..0cdbbd8 --- /dev/null +++ b/node_modules/which-boxed-primitive/.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/which-boxed-primitive +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/which-boxed-primitive/.nycrc b/node_modules/which-boxed-primitive/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/which-boxed-primitive/.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/which-boxed-primitive/CHANGELOG.md b/node_modules/which-boxed-primitive/CHANGELOG.md new file mode 100644 index 0000000..23e5422 --- /dev/null +++ b/node_modules/which-boxed-primitive/CHANGELOG.md @@ -0,0 +1,54 @@ +# 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/which-boxed-primitive/compare/v1.0.1...v1.0.2) - 2020-12-14 + +### Commits + +- [Tests] use shared travis-ci configs [`8674582`](https://github.com/inspect-js/which-boxed-primitive/commit/86745829b6a92cff2cfb0d3c0414ec9afdc2a087) +- [Tests] migrate tests to Github Actions [`dff6643`](https://github.com/inspect-js/which-boxed-primitive/commit/dff6643405ba4d6dc6694a25904c8f72f273ece8) +- [meta] do not publish github action workflow files [`b26112a`](https://github.com/inspect-js/which-boxed-primitive/commit/b26112a4e4ac6beec8f54c734135dbf9e9ba16f9) +- [meta] make `auto-changelog` config consistent [`8d10175`](https://github.com/inspect-js/which-boxed-primitive/commit/8d10175171154cd6c8f8a016aa7fb71b5044acf6) +- [readme] fix repo URLs, remove defunct badges [`ab8db24`](https://github.com/inspect-js/which-boxed-primitive/commit/ab8db247573723dbcda68469118d08c7c2692c67) +- [Tests] run `nyc` on all tests; use `tape` runner [`7d084df`](https://github.com/inspect-js/which-boxed-primitive/commit/7d084dfc5251230e9399a81782c0b9d7ae5d1901) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`576f6f3`](https://github.com/inspect-js/which-boxed-primitive/commit/576f6f308aed35ef1d3392bb9472def59482ed13) +- [actions] add automatic rebasing / merge commit blocking [`97efa53`](https://github.com/inspect-js/which-boxed-primitive/commit/97efa53a307678323e63f576c07db9ff84846fd3) +- [actions] add "Allow Edits" workflow [`fb1b4f7`](https://github.com/inspect-js/which-boxed-primitive/commit/fb1b4f7cd753fcced74ac054b20c8b2bfafe7953) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `has-symbols`, `object-inspect`, `safe-publish-latest` [`1e03c61`](https://github.com/inspect-js/which-boxed-primitive/commit/1e03c6153693d385833acc15178f675e6ce5ddd0) +- [Deps] update `is-boolean-object`, `is-number-object`, `is-string`, `is-symbol` [`13673df`](https://github.com/inspect-js/which-boxed-primitive/commit/13673dff6e43f0a915377c3e5740ec24e86d6bb7) +- [Dev Deps] update `auto-changelog`, `in-publish`, `tape` [`65a0e15`](https://github.com/inspect-js/which-boxed-primitive/commit/65a0e155fc46a9237692233a51ec9573621135d2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`f8a0afe`](https://github.com/inspect-js/which-boxed-primitive/commit/f8a0afea82938d64f3d2d240268afbd346d0c4da) +- [Deps] update `is-bigint`, `is-boolean-object` [`e7a1ce2`](https://github.com/inspect-js/which-boxed-primitive/commit/e7a1ce25371c00ee726f1c0cc5b6acf10d51ec50) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`e46f193`](https://github.com/inspect-js/which-boxed-primitive/commit/e46f193298b158db5c8aba889803513e4ee38957) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`df3da14`](https://github.com/inspect-js/which-boxed-primitive/commit/df3da1424552a5d22e203a0abf1710106bfd4ae2) +- [Dev Deps] update `auto-changelog`; add `aud` [`e2e8a12`](https://github.com/inspect-js/which-boxed-primitive/commit/e2e8a12c6fbf8c48e760ea1d1ccd5e8d2d6fbf24) +- [meta] add `funding` field [`7df404b`](https://github.com/inspect-js/which-boxed-primitive/commit/7df404b20cd50b2b87e6645b130fefa8ee98810e) +- [Dev Deps] update `auto-changelog` [`0d6b76d`](https://github.com/inspect-js/which-boxed-primitive/commit/0d6b76dbbe760581fa86a0c3f254988fe5d27770) +- [Tests] only audit prod deps [`246151c`](https://github.com/inspect-js/which-boxed-primitive/commit/246151cc1407b3b1ef42014db993f62670bd82ff) +- [meta] fix changelog [`c2d1685`](https://github.com/inspect-js/which-boxed-primitive/commit/c2d16856deffbf86e0b5029e69b65d8aa758ec3d) +- [readme] Fix spelling error [`25fb2b5`](https://github.com/inspect-js/which-boxed-primitive/commit/25fb2b56e1f708c6364923e4bae384f818ecf57f) + +## [v1.0.1](https://github.com/inspect-js/which-boxed-primitive/compare/v1.0.0...v1.0.1) - 2019-08-10 + +### Commits + +- [meta] avoid running `safe-publish-latest` when not publishing [`df44b27`](https://github.com/inspect-js/which-boxed-primitive/commit/df44b27875a8f5c3c596663ecb4a063f9fc7bde3) + +## v1.0.0 - 2019-08-10 + +### Commits + +- [Tests] add `.travis.yml` [`764b0cf`](https://github.com/inspect-js/which-boxed-primitive/commit/764b0cf75f8d2b3a0ad2056de5f4ad85d5d1b765) +- Initial commit [`da7d068`](https://github.com/inspect-js/which-boxed-primitive/commit/da7d068913d591294bf155db5d438f7804d71b9a) +- readme [`1395bb2`](https://github.com/inspect-js/which-boxed-primitive/commit/1395bb27b72137ac01e48ee398a0f54e93fd87f5) +- [Tests] add tests [`0ff580f`](https://github.com/inspect-js/which-boxed-primitive/commit/0ff580f99579cd4424af7b814bd76fcb69a2b04e) +- implementation [`8811c32`](https://github.com/inspect-js/which-boxed-primitive/commit/8811c3262a57963634cdc83ceb5bb2c5e9ae4e7e) +- npm init [`cffdea9`](https://github.com/inspect-js/which-boxed-primitive/commit/cffdea9755eabfa2f9ec62a6fcbce0c28f04495b) +- [Tests] add `npm run lint` [`a8be993`](https://github.com/inspect-js/which-boxed-primitive/commit/a8be9933fec1b21267acd847df77f6438e07e3b9) +- [meta] add FUNDING.yml [`941258c`](https://github.com/inspect-js/which-boxed-primitive/commit/941258c70c9a397466e05b614126cb8c7be77b99) +- Only apps should have lockfiles [`6857316`](https://github.com/inspect-js/which-boxed-primitive/commit/68573165d8ce842cdf15d94af82f8cccb961b8cf) +- [Tests] use `npx aud` in `posttest` [`ee48a91`](https://github.com/inspect-js/which-boxed-primitive/commit/ee48a9144bea23bde5cc47788a54d5aa7969d489) diff --git a/node_modules/which-boxed-primitive/LICENSE b/node_modules/which-boxed-primitive/LICENSE new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/node_modules/which-boxed-primitive/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/which-boxed-primitive/README.md b/node_modules/which-boxed-primitive/README.md new file mode 100644 index 0000000..e08f26a --- /dev/null +++ b/node_modules/which-boxed-primitive/README.md @@ -0,0 +1,73 @@ +# which-boxed-primitive [![Version Badge][2]][1] + +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Which kind of boxed JS primitive is this? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and works despite ES6 Symbol.toStringTag. + +## Example + +```js +var whichBoxedPrimitive = require('which-boxed-primitive'); +var assert = require('assert'); + +// unboxed primitives return `null` +// boxed primitives return the builtin constructor name + +assert.equal(whichBoxedPrimitive(undefined), null); +assert.equal(whichBoxedPrimitive(null), null); + +assert.equal(whichBoxedPrimitive(false), null); +assert.equal(whichBoxedPrimitive(true), null); +assert.equal(whichBoxedPrimitive(new Boolean(false)), 'Boolean'); +assert.equal(whichBoxedPrimitive(new Boolean(true)), 'Boolean'); + +assert.equal(whichBoxedPrimitive(42), null); +assert.equal(whichBoxedPrimitive(NaN), null); +assert.equal(whichBoxedPrimitive(Infinity), null); +assert.equal(whichBoxedPrimitive(new Number(42)), 'Number'); +assert.equal(whichBoxedPrimitive(new Number(NaN)), 'Number'); +assert.equal(whichBoxedPrimitive(new Number(Infinity)), 'Number'); + +assert.equal(whichBoxedPrimitive(''), null); +assert.equal(whichBoxedPrimitive('foo'), null); +assert.equal(whichBoxedPrimitive(new String('')), 'String'); +assert.equal(whichBoxedPrimitive(new String('foo')), 'String'); + +assert.equal(whichBoxedPrimitive(Symbol()), null); +assert.equal(whichBoxedPrimitive(Object(Symbol()), 'Symbol'); + +assert.equal(whichBoxedPrimitive(42n), null); +assert.equal(whichBoxedPrimitive(Object(42n), 'BigInt'); + +// non-boxed-primitive objects return `undefined` +assert.equal(whichBoxedPrimitive([]), undefined); +assert.equal(whichBoxedPrimitive({}), undefined); +assert.equal(whichBoxedPrimitive(/a/g), undefined); +assert.equal(whichBoxedPrimitive(new RegExp('a', 'g')), undefined); +assert.equal(whichBoxedPrimitive(new Date()), undefined); +assert.equal(whichBoxedPrimitive(function () {}), undefined); +assert.equal(whichBoxedPrimitive(function* () {}), undefined); +assert.equal(whichBoxedPrimitive(x => x * x), undefined); +assert.equal(whichBoxedPrimitive([]), undefined); + +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/which-boxed-primitive +[2]: https://versionbadg.es/inspect-js/which-boxed-primitive.svg +[5]: https://david-dm.org/inspect-js/which-boxed-primitive.svg +[6]: https://david-dm.org/inspect-js/which-boxed-primitive +[7]: https://david-dm.org/inspect-js/which-boxed-primitive/dev-status.svg +[8]: https://david-dm.org/inspect-js/which-boxed-primitive#info=devDependencies +[11]: https://nodei.co/npm/which-boxed-primitive.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/which-boxed-primitive.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/which-boxed-primitive.svg +[downloads-url]: https://npm-stat.com/charts.html?package=which-boxed-primitive diff --git a/node_modules/which-boxed-primitive/index.js b/node_modules/which-boxed-primitive/index.js new file mode 100644 index 0000000..f8ea564 --- /dev/null +++ b/node_modules/which-boxed-primitive/index.js @@ -0,0 +1,30 @@ +'use strict'; + +var isString = require('is-string'); +var isNumber = require('is-number-object'); +var isBoolean = require('is-boolean-object'); +var isSymbol = require('is-symbol'); +var isBigInt = require('is-bigint'); + +// eslint-disable-next-line consistent-return +module.exports = function whichBoxedPrimitive(value) { + // eslint-disable-next-line eqeqeq + if (value == null || (typeof value !== 'object' && typeof value !== 'function')) { + return null; + } + if (isString(value)) { + return 'String'; + } + if (isNumber(value)) { + return 'Number'; + } + if (isBoolean(value)) { + return 'Boolean'; + } + if (isSymbol(value)) { + return 'Symbol'; + } + if (isBigInt(value)) { + return 'BigInt'; + } +}; diff --git a/node_modules/which-boxed-primitive/package.json b/node_modules/which-boxed-primitive/package.json new file mode 100644 index 0000000..0ef53eb --- /dev/null +++ b/node_modules/which-boxed-primitive/package.json @@ -0,0 +1,65 @@ +{ + "name": "which-boxed-primitive", + "version": "1.0.2", + "description": "Which kind of boxed JS primitive is this?", + "main": "index.js", + "scripts": { + "preversion": "auto-changelog", + "prepublish": "not-in-publish || safe-publish-latest", + "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/inspect-js/which-boxed-primitive.git" + }, + "keywords": [ + "boxed", + "primitive", + "object", + "ecmascript", + "javascript", + "which" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/which-boxed-primitive/issues" + }, + "homepage": "https://github.com/inspect-js/which-boxed-primitive#readme", + "dependencies": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.3.0", + "aud": "^1.1.3", + "auto-changelog": "^2.2.1", + "eslint": "^7.15.0", + "has-symbols": "^1.0.1", + "in-publish": "^2.0.1", + "nyc": "^10.3.2", + "object-inspect": "^1.9.0", + "safe-publish-latest": "^1.1.4", + "tape": "^5.0.1" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/which-boxed-primitive/test/index.js b/node_modules/which-boxed-primitive/test/index.js new file mode 100644 index 0000000..f9ea998 --- /dev/null +++ b/node_modules/which-boxed-primitive/test/index.js @@ -0,0 +1,66 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var whichBoxedPrimitive = require('..'); + +var debug = function (v, m) { return inspect(v) + ' ' + m; }; + +var forEach = function (arr, func) { + var i; + for (i = 0; i < arr.length; ++i) { + func(arr[i], i, arr); + } +}; + +var hasSymbols = require('has-symbols')(); +var hasBigInts = typeof BigInt === 'function'; + +var primitives = [ + true, + false, + 42, + NaN, + Infinity, + '', + 'foo' +].concat( + hasSymbols ? [Symbol(), Symbol.iterator] : [], + hasBigInts ? BigInt(42) : [] +); + +var objects = [ + /a/g, + new Date(), + function () {}, + [], + {} +]; + +test('isBoxedPrimitive', function (t) { + t.test('unboxed primitives', function (st) { + forEach([null, undefined].concat(primitives), function (primitive) { + st.equal(null, whichBoxedPrimitive(primitive), debug(primitive, 'is a primitive, but not a boxed primitive')); + }); + st.end(); + }); + + t.test('boxed primitives', function (st) { + forEach(primitives, function (primitive) { + var boxed = Object(primitive); + var expected = boxed.constructor.name; + st.equal(typeof expected, 'string', 'expected is string'); + st.equal(whichBoxedPrimitive(boxed), expected, debug(boxed, 'is a boxed primitive: ' + expected)); + }); + st.end(); + }); + + t.test('non-primitive objects', function (st) { + forEach(objects, function (object) { + st.equal(undefined, whichBoxedPrimitive(object), debug(object, 'is not a primitive, boxed or otherwise')); + }); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/which-collection/.eslintrc b/node_modules/which-collection/.eslintrc new file mode 100644 index 0000000..4d08f25 --- /dev/null +++ b/node_modules/which-collection/.eslintrc @@ -0,0 +1,15 @@ +{ + "root": true, + + "extends": "@ljharb", + + "overrides": [ + { + "files": "test/**", + "globals": { + "WeakMap": false, + "WeakSet": false, + }, + }, + ], +} diff --git a/node_modules/which-collection/.github/FUNDING.yml b/node_modules/which-collection/.github/FUNDING.yml new file mode 100644 index 0000000..7570eaa --- /dev/null +++ b/node_modules/which-collection/.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/which-collection +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/which-collection/.github/workflows/rebase.yml b/node_modules/which-collection/.github/workflows/rebase.yml new file mode 100644 index 0000000..436cb79 --- /dev/null +++ b/node_modules/which-collection/.github/workflows/rebase.yml @@ -0,0 +1,15 @@ +name: Automatic Rebase + +on: [pull_request] + +jobs: + _: + name: "Automatic Rebase" + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - uses: ljharb/rebase@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/which-collection/.travis.yml b/node_modules/which-collection/.travis.yml new file mode 100644 index 0000000..5ed0fa5 --- /dev/null +++ b/node_modules/which-collection/.travis.yml @@ -0,0 +1,8 @@ +version: ~> 1.0 +language: node_js +os: + - linux +import: + - ljharb/travis-ci:node/all.yml + - ljharb/travis-ci:node/pretest.yml + - ljharb/travis-ci:node/posttest.yml diff --git a/node_modules/which-collection/CHANGELOG.md b/node_modules/which-collection/CHANGELOG.md new file mode 100644 index 0000000..62d2da6 --- /dev/null +++ b/node_modules/which-collection/CHANGELOG.md @@ -0,0 +1,33 @@ +# 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). + +Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). + +## [v1.0.1](https://github.com/inspect-js/which-collection/compare/v1.0.0...v1.0.1) - 2020-01-26 + +### Commits + +- [actions] add automatic rebasing / merge commit blocking [`c3820b2`](https://github.com/inspect-js/which-collection/commit/c3820b2e8c88548f2c7da4080b1d1b6b41be97a4) +- [patch] add "exports" [`10983b5`](https://github.com/inspect-js/which-collection/commit/10983b5fdcc453c64216c3d6aa3fb93340091818) +- [Deps] update `is-map`, `is-set`, `is-weakmap`, `is-weakset` [`1565925`](https://github.com/inspect-js/which-collection/commit/1565925705c4abfe88065b211d1d960791f7cd3c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`92ef871`](https://github.com/inspect-js/which-collection/commit/92ef871338395352f1bafc3156088361a3fd917a) +- [Dev Deps] update `@ljharb/eslint-config` [`61e9cde`](https://github.com/inspect-js/which-collection/commit/61e9cde1830ccc2b551dd6a1a873ae2cf27a74c7) + +## v1.0.0 - 2019-11-13 + +### Commits + +- Initial commit [`a21fddf`](https://github.com/inspect-js/which-collection/commit/a21fddffef3b2f21923e4d056295dd63661d8155) +- Tests [`ec86bc1`](https://github.com/inspect-js/which-collection/commit/ec86bc12f0516bd662c6e2966b36de2e1128a431) +- readme [`ffe969c`](https://github.com/inspect-js/which-collection/commit/ffe969cf4388d18e12c664cc51498bbdef08e565) +- implementation [`9acb669`](https://github.com/inspect-js/which-collection/commit/9acb6695e6a5e60f4c0b6de59eaf8b1f681d78e5) +- npm init [`124a63e`](https://github.com/inspect-js/which-collection/commit/124a63ee68a0015b47cbcc08b0d5598e553e7c9a) +- [meta] add `auto-changelog`, `safe-publish-latest` [`df0d6d4`](https://github.com/inspect-js/which-collection/commit/df0d6d4f1efbc4d9b327471b9c659bd487b25b49) +- [meta] add `funding` field; create FUNDING.yml [`032c81c`](https://github.com/inspect-js/which-collection/commit/032c81c826d68acd6242fa87fd6348db70135506) +- [Tests] add `npm run lint` [`6ae406d`](https://github.com/inspect-js/which-collection/commit/6ae406d9e459779abbdd90f48559552f740b05c9) +- fixup [`a2cad36`](https://github.com/inspect-js/which-collection/commit/a2cad363f12e30afe7619597187c5d4dc840a2a7) +- Only apps should have lockfiles [`30b3aae`](https://github.com/inspect-js/which-collection/commit/30b3aae37155f0786e4582501369f738b3282cd7) diff --git a/node_modules/which-collection/LICENSE b/node_modules/which-collection/LICENSE new file mode 100644 index 0000000..c05eb20 --- /dev/null +++ b/node_modules/which-collection/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 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/which-collection/README.md b/node_modules/which-collection/README.md new file mode 100644 index 0000000..ae5e99a --- /dev/null +++ b/node_modules/which-collection/README.md @@ -0,0 +1,64 @@ +# which-collection [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Which kind of Collection (Map, Set, WeakMap, WeakSet) is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag. + +## Example + +```js +var whichCollection = require('which-collection'); +var assert = require('assert'); + +assert.equal(false, whichCollection(undefined)); +assert.equal(false, whichCollection(null)); +assert.equal(false, whichCollection(false)); +assert.equal(false, whichCollection(true)); +assert.equal(false, whichCollection([])); +assert.equal(false, whichCollection({})); +assert.equal(false, whichCollection(/a/g)); +assert.equal(false, whichCollection(new RegExp('a', 'g'))); +assert.equal(false, whichCollection(new Date())); +assert.equal(false, whichCollection(42)); +assert.equal(false, whichCollection(NaN)); +assert.equal(false, whichCollection(Infinity)); +assert.equal(false, whichCollection(new Number(42))); +assert.equal(false, whichCollection(42n)); +assert.equal(false, whichCollection(Object(42n))); +assert.equal(false, whichCollection('foo')); +assert.equal(false, whichCollection(Object('foo'))); +assert.equal(false, whichCollection(function () {})); +assert.equal(false, whichCollection(function* () {})); +assert.equal(false, whichCollection(x => x * x)); +assert.equal(false, whichCollection([])); + +assert.equal('Map', whichCollection(new Map())); +assert.equal('Set', whichCollection(new Set())); +assert.equal('WeakMap', whichCollection(new WeakMap())); +assert.equal('WeakSet', whichCollection(new WeakSet())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/which-collection +[2]: http://versionbadg.es/inspect-js/which-collection.svg +[3]: https://travis-ci.org/inspect-js/which-collection.svg +[4]: https://travis-ci.org/inspect-js/which-collection +[5]: https://david-dm.org/inspect-js/which-collection.svg +[6]: https://david-dm.org/inspect-js/which-collection +[7]: https://david-dm.org/inspect-js/which-collection/dev-status.svg +[8]: https://david-dm.org/inspect-js/which-collection#info=devDependencies +[9]: https://ci.testling.com/inspect-js/which-collection.png +[10]: https://ci.testling.com/inspect-js/which-collection +[11]: https://nodei.co/npm/which-collection.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/which-collection.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/which-collection.svg +[downloads-url]: http://npm-stat.com/charts.html?package=which-collection diff --git a/node_modules/which-collection/index.js b/node_modules/which-collection/index.js new file mode 100644 index 0000000..71c7f95 --- /dev/null +++ b/node_modules/which-collection/index.js @@ -0,0 +1,24 @@ +'use strict'; + +var isMap = require('is-map'); +var isSet = require('is-set'); +var isWeakMap = require('is-weakmap'); +var isWeakSet = require('is-weakset'); + +module.exports = function whichCollection(value) { + if (value && typeof value === 'object') { + if (isMap(value)) { + return 'Map'; + } + if (isSet(value)) { + return 'Set'; + } + if (isWeakMap(value)) { + return 'WeakMap'; + } + if (isWeakSet(value)) { + return 'WeakSet'; + } + } + return false; +}; diff --git a/node_modules/which-collection/package.json b/node_modules/which-collection/package.json new file mode 100644 index 0000000..985878c --- /dev/null +++ b/node_modules/which-collection/package.json @@ -0,0 +1,69 @@ +{ + "name": "which-collection", + "version": "1.0.1", + "description": "Which kind of Collection (Map, Set, WeakMap, WeakSet) is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag.", + "main": "index.js", + "type": "commonjs", + "exports": { + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "prepublish": "safe-publish-latest", + "lint": "eslint .", + "pretest": "npm run lint", + "tests-only": "node test", + "test": "npm run tests-only", + "posttest": "npx aud", + "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/which-collection.git" + }, + "keywords": [ + "map", + "set", + "weakmap", + "weakset", + "collection.es6", + "es2015" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/which-collection/issues" + }, + "homepage": "https://github.com/inspect-js/which-collection#readme", + "devDependencies": { + "@ljharb/eslint-config": "^16.0.0", + "auto-changelog": "^1.16.2", + "eslint": "^6.8.0", + "for-each": "^0.3.3", + "object-inspect": "^1.7.0", + "safe-publish-latest": "^1.1.4", + "tape": "^5.0.0-next.4" + }, + "dependencies": { + "is-map": "^2.0.1", + "is-set": "^2.0.1", + "is-weakmap": "^2.0.1", + "is-weakset": "^2.0.1" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false + } +} diff --git a/node_modules/which-collection/test/index.js b/node_modules/which-collection/test/index.js new file mode 100644 index 0000000..3a5becc --- /dev/null +++ b/node_modules/which-collection/test/index.js @@ -0,0 +1,59 @@ +'use strict'; + +var test = require('tape'); +var debug = require('object-inspect'); +var forEach = require('for-each'); + +var whichCollection = require('..'); + +test('non-collections', function (t) { + forEach([ + null, + undefined, + true, + false, + 42, + 0, + -0, + NaN, + Infinity, + '', + 'foo', + /a/g, + [], + {}, + function () {} + ], function (nonCollection) { + t.equal(whichCollection(nonCollection), false, debug(nonCollection) + ' is not a collection'); + }); + + t.end(); +}); + +test('Maps', { skip: typeof Map !== 'function' }, function (t) { + var m = new Map(); + t.equal(whichCollection(m), 'Map', debug(m) + ' is a Map'); + + t.end(); +}); + +test('Sets', { skip: typeof Set !== 'function' }, function (t) { + var s = new Set(); + t.equal(whichCollection(s), 'Set', debug(s) + ' is a Set'); + + t.end(); +}); + +test('WeakMaps', { skip: typeof WeakMap !== 'function' }, function (t) { + var wm = new WeakMap(); + t.equal(whichCollection(wm), 'WeakMap', debug(wm) + ' is a WeakMap'); + + t.end(); +}); + +test('WeakSets', { skip: typeof WeakSet !== 'function' }, function (t) { + var ws = new WeakSet(); + t.equal(whichCollection(ws), 'WeakSet', debug(ws) + ' is a WeakSet'); + + t.end(); +}); diff --git a/node_modules/which-typed-array/.editorconfig b/node_modules/which-typed-array/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/node_modules/which-typed-array/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/which-typed-array/.eslintrc b/node_modules/which-typed-array/.eslintrc new file mode 100644 index 0000000..8b2ada0 --- /dev/null +++ b/node_modules/which-typed-array/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + }, +} diff --git a/node_modules/which-typed-array/.github/FUNDING.yml b/node_modules/which-typed-array/.github/FUNDING.yml new file mode 100644 index 0000000..d6aa180 --- /dev/null +++ b/node_modules/which-typed-array/.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/which-typed-array +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/which-typed-array/.nycrc b/node_modules/which-typed-array/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/which-typed-array/.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/which-typed-array/CHANGELOG.md b/node_modules/which-typed-array/CHANGELOG.md new file mode 100644 index 0000000..c1b2cb5 --- /dev/null +++ b/node_modules/which-typed-array/CHANGELOG.md @@ -0,0 +1,175 @@ +# 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.9](https://github.com/inspect-js/which-typed-array/compare/v1.1.8...v1.1.9) - 2022-11-02 + +### Commits + +- [Dev Deps] update `aud`, `is-callable`, `tape` [`9a20b3c`](https://github.com/inspect-js/which-typed-array/commit/9a20b3cb8f5d087789a8160395517bffe27b4339) +- [Refactor] use `gopd` instead of `es-abstract` helper [`00157af`](https://github.com/inspect-js/which-typed-array/commit/00157af909842b8b5affa5485d3574ec92d94065) +- [Deps] update `is-typed-array` [`6714240`](https://github.com/inspect-js/which-typed-array/commit/6714240e748cbbb634cb1e405ad762bc52acde66) +- [meta] add `sideEffects` flag [`89b96cc`](https://github.com/inspect-js/which-typed-array/commit/89b96cc3decc78d9621598e94fa1c2bb87eabf2e) + +## [v1.1.8](https://github.com/inspect-js/which-typed-array/compare/v1.1.7...v1.1.8) - 2022-05-14 + +### Commits + +- [actions] reuse common workflows [`95ea6c0`](https://github.com/inspect-js/which-typed-array/commit/95ea6c02dc5ec4ed0ee1b9c4692bb060108c8637) +- [meta] use `npmignore` to autogenerate an npmignore file [`d08436a`](https://github.com/inspect-js/which-typed-array/commit/d08436a19cdd76219732f5040a01cdb92ef2820e) +- [readme] add github actions/codecov badges [`35ae3af`](https://github.com/inspect-js/which-typed-array/commit/35ae3af6a0bb328c9d9b9bbb53e47122f269d81a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`86e6e3a`](https://github.com/inspect-js/which-typed-array/commit/86e6e3af60b2436f0ff34968d9d6240a23f40528) +- [actions] update codecov uploader [`0aa6e30`](https://github.com/inspect-js/which-typed-array/commit/0aa6e3026ab4198c4364737ed4f0315a2ecc432a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`a881a78`](https://github.com/inspect-js/which-typed-array/commit/a881a785f094e823e1cefe2ae9e4ebe31a8e996e) +- [Refactor] use `for-each` instead of `foreach` [`9dafa03`](https://github.com/inspect-js/which-typed-array/commit/9dafa0377fc5c690059a9d454f1dd4d365c5c902) +- [Deps] update `es-abstract`, `is-typed-array` [`0684022`](https://github.com/inspect-js/which-typed-array/commit/068402297608f321a4ec99ebce741b3eb38fcfdd) +- [Deps] update `es-abstract`, `is-typed-array` [`633a529`](https://github.com/inspect-js/which-typed-array/commit/633a529081b5c48d9675abb8aea425e6e33d528e) + +## [v1.1.7](https://github.com/inspect-js/which-typed-array/compare/v1.1.6...v1.1.7) - 2021-08-30 + +### Commits + +- [Refactor] use `globalThis` if available [`2a16d1f`](https://github.com/inspect-js/which-typed-array/commit/2a16d1fd520871ce6b23c60f0bd2113cf33b2533) +- [meta] changelog cleanup [`ba99f56`](https://github.com/inspect-js/which-typed-array/commit/ba99f56b45e6acde7aef4a1f34bb00e44088ccee) +- [Dev Deps] update `@ljharb/eslint-config` [`19a6e04`](https://github.com/inspect-js/which-typed-array/commit/19a6e04ce0094fb3fd6d0d2cbc58d320556ddf50) +- [Deps] update `available-typed-arrays` [`50dbc58`](https://github.com/inspect-js/which-typed-array/commit/50dbc5810a24c468b49409e1f0a79d03501e3dd6) +- [Deps] update `is-typed-array` [`c1b83ea`](https://github.com/inspect-js/which-typed-array/commit/c1b83eae65f042e46b6ae941ac4e814b7965a0f7) + +## [v1.1.6](https://github.com/inspect-js/which-typed-array/compare/v1.1.5...v1.1.6) - 2021-08-06 + +### Fixed + +- [Fix] if Symbol.toStringTag exists but is not present, use Object.prototype.toString [`#51`](https://github.com/inspect-js/which-typed-array/issues/51) [`#49`](https://github.com/inspect-js/which-typed-array/issues/49) + +### Commits + +- [Dev Deps] update `is-callable`, `tape` [`63eb1e3`](https://github.com/inspect-js/which-typed-array/commit/63eb1e3faede3f328bbbb4a5fcffc2e4769cf4ec) +- [Deps] update `is-typed-array` [`c5056f0`](https://github.com/inspect-js/which-typed-array/commit/c5056f0007d4c9434f1fa69eff183109468b4769) + +## [v1.1.5](https://github.com/inspect-js/which-typed-array/compare/v1.1.4...v1.1.5) - 2021-08-05 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`63fa8dd`](https://github.com/inspect-js/which-typed-array/commit/63fa8dd1dc9c0f0dbbaa16d1de0eb89797324c5d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `is-callable`, `tape` [`1107c74`](https://github.com/inspect-js/which-typed-array/commit/1107c74c52ed6eb4a719faec88e16c4343976d73) +- [Deps] update `available-typed-arrays`, `call-bind`, `es-abstract`, `is-typed-array` [`f953454`](https://github.com/inspect-js/which-typed-array/commit/f953454b2c6f589f09573ddc961431f970c2e1b6) +- [Fix] use `has-tostringtag` to behave correctly in the presence of symbol shams [`8aee720`](https://github.com/inspect-js/which-typed-array/commit/8aee7207abcd72c799ac324b214fbb6ca7ae4a28) +- [meta] use `prepublishOnly` script for npm 7+ [`6c5167b`](https://github.com/inspect-js/which-typed-array/commit/6c5167b4cd06cb62a5487a2e797d8e41cc2970b1) + +## [v1.1.4](https://github.com/inspect-js/which-typed-array/compare/v1.1.3...v1.1.4) - 2020-12-05 + +### Commits + +- [meta] npmignore github action workflows [`aa427e7`](https://github.com/inspect-js/which-typed-array/commit/aa427e79a230a985953695a8129ceb6bb7d42527) + +## [v1.1.3](https://github.com/inspect-js/which-typed-array/compare/v1.1.2...v1.1.3) - 2020-12-05 + +### Commits + +- [Tests] migrate tests to Github Actions [`803d4dd`](https://github.com/inspect-js/which-typed-array/commit/803d4ddb601ff03e587be792bd452de0e2783d03) +- [Tests] run `nyc` on all tests [`205a13f`](https://github.com/inspect-js/which-typed-array/commit/205a13f7aa172e014ddc2079c84af6ba575581c8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `is-callable`, `tape` [`97ceb07`](https://github.com/inspect-js/which-typed-array/commit/97ceb070d5aea1c3a696c6f695800ae468bafc0b) +- [actions] add "Allow Edits" workflow [`b140492`](https://github.com/inspect-js/which-typed-array/commit/b14049211eff32bd4149767def4f939483810051) +- [Deps] update `es-abstract`; use `call-bind` where applicable [`2abdb87`](https://github.com/inspect-js/which-typed-array/commit/2abdb871961b4e1b58925115a7d56a9cc5966a02) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`256d34b`](https://github.com/inspect-js/which-typed-array/commit/256d34b8bdb67b8af0e9f83c9a318e54f3340e3b) +- [Dev Deps] update `auto-changelog`; add `aud` [`ddea96f`](https://github.com/inspect-js/which-typed-array/commit/ddea96fe320dbdd0c7d7569812399a7f64d43e04) +- [meta] gitignore nyc output [`8a812bd`](https://github.com/inspect-js/which-typed-array/commit/8a812bd1ce7c5609988fb4fe2e9af2089eccd07d) + +## [v1.1.2](https://github.com/inspect-js/which-typed-array/compare/v1.1.1...v1.1.2) - 2020-04-07 + +### Commits + +- [Dev Deps] update `make-arrow-function`, `make-generator-function` [`28c61ef`](https://github.com/inspect-js/which-typed-array/commit/28c61eff4903ff6509f65c2f500858b9cb4636f1) +- [Dev Deps] update `@ljharb/eslint-config` [`a233879`](https://github.com/inspect-js/which-typed-array/commit/a2338798d3a4a3169cda54e322b2f2eb0e976ad0) +- [Dev Deps] update `auto-changelog` [`df0134c`](https://github.com/inspect-js/which-typed-array/commit/df0134c0e20ec6d94993988ad670e1b3cf350bea) +- [Fix] move `foreach` to dependencies [`6ef29c0`](https://github.com/inspect-js/which-typed-array/commit/6ef29c0dbb91a7ec21df7ce8736f99f41efea39e) +- [Tests] only audit prod deps [`eb21044`](https://github.com/inspect-js/which-typed-array/commit/eb210446bd7a433657204d2314ef56fe264c21ad) +- [Deps] update `es-abstract` [`5ef0236`](https://github.com/inspect-js/which-typed-array/commit/5ef02368d9876a1074123aa7725d6759b4f3e358) +- [Dev Deps] update `tape` [`7456037`](https://github.com/inspect-js/which-typed-array/commit/745603728c6c3da8bdddee321e8a9196f4827aa3) +- [Deps] update `available-typed-arrays` [`8a856c9`](https://github.com/inspect-js/which-typed-array/commit/8a856c9aa707c1e6f7a52e834485356b31395ea6) + +## [v1.1.1](https://github.com/inspect-js/which-typed-array/compare/v1.1.0...v1.1.1) - 2020-01-24 + +### Commits + +- [Tests] use shared travis-ci configs [`0a627d9`](https://github.com/inspect-js/which-typed-array/commit/0a627d9694d0eabdaee63b19e605584166995a79) +- [meta] add `auto-changelog` [`2a14c58`](https://github.com/inspect-js/which-typed-array/commit/2a14c58b79f72e32ef2078efb40d31a4bf8c197a) +- [meta] remove unused Makefile and associated utilities [`75f7f22`](https://github.com/inspect-js/which-typed-array/commit/75f7f222199f42618c290de363c542b11f5a5632) +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`4162327`](https://github.com/inspect-js/which-typed-array/commit/416232725e7d127cbd886af0f8988dae612a342f) +- [Refactor] use `es-abstract`’s `callBound`, `available-typed-arrays`, `has-symbols` [`9b04a2a`](https://github.com/inspect-js/which-typed-array/commit/9b04a2a14c758600cffcf59485b7b3c85839c266) +- [readme] fix repo URLs, remove testling [`03ed52f`](https://github.com/inspect-js/which-typed-array/commit/03ed52f3ae4fcd35614bcda7e947b14e62009c71) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `replace`, `semver`, `tape` [`bfbcf3e`](https://github.com/inspect-js/which-typed-array/commit/bfbcf3ec9c449bd0089ed805c01a32ba4e7e5938) +- [actions] add automatic rebasing / merge commit blocking [`cc88ac5`](https://github.com/inspect-js/which-typed-array/commit/cc88ac56bcfb71cb26c656ebde4c560a22fadd85) +- [meta] create FUNDING.yml [`acbc723`](https://github.com/inspect-js/which-typed-array/commit/acbc7230929b1256c83df28be4a456eed3e147e9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is-callable`, `tape` [`f1ab63e`](https://github.com/inspect-js/which-typed-array/commit/f1ab63e9366027eae2e29398c035181dac164132) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` [`ac9f50b`](https://github.com/inspect-js/which-typed-array/commit/ac9f50b59558933292dff993df2e68eaa44b07e2) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`aaaa15d`](https://github.com/inspect-js/which-typed-array/commit/aaaa15dfb5bd8228c0cfb8f2aba267efb405b0a1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`602fc9a`](https://github.com/inspect-js/which-typed-array/commit/602fc9a0a7d708236f90c76f592e6a980ecde940) +- [Deps] update `available-typed-arrays`, `is-typed-array` [`b2d69b6`](https://github.com/inspect-js/which-typed-array/commit/b2d69b639bf14344d09f8512dbc060cd4f533161) +- [meta] add `funding` field [`156f613`](https://github.com/inspect-js/which-typed-array/commit/156f613d0ce547c4b15e1ae279198b66e3cef55e) + +## [v1.1.0](https://github.com/inspect-js/which-typed-array/compare/v1.0.1...v1.1.0) - 2019-02-16 + +### Commits + +- [Tests] remove `jscs` [`381c9b4`](https://github.com/inspect-js/which-typed-array/commit/381c9b4bd858da1adedf23d8555af3a3ed901a83) +- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`, `v5.8`; improve matrix; newer npm breaks on older node [`7015c19`](https://github.com/inspect-js/which-typed-array/commit/7015c196ba86540b04d18d9b1d2c368909492023) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9`; use `nvm install-latest-npm` [`ad67885`](https://github.com/inspect-js/which-typed-array/commit/ad678853e245986720d7650be1c974a9ff3ac814) +- [Tests] up to `node` `v11.6`, `v10.15`, `v8.15`, `v6.16` [`dd94bfb`](https://github.com/inspect-js/which-typed-array/commit/dd94bfb6309a92d1537352f2d1100f9e913ebc01) +- [Refactor] use an array instead of an object for storing Typed Array names [`de98bc1`](https://github.com/inspect-js/which-typed-array/commit/de98bc1d44af92909a34212e276deb5d79ac428a) +- [meta] ignore `test.html` [`06cfb1b`](https://github.com/inspect-js/which-typed-array/commit/06cfb1bc0ca7881d1bd1621fa946a16366cd6afc) +- [Tests] up to `node` `v7.0`, `v6.9`, `v4.6`; improve test matrix [`df76eaa`](https://github.com/inspect-js/which-typed-array/commit/df76eaa39b94b28147e81a89bb587e8aa3e3dba3) +- [New] add `BigInt64Array` and `BigUint64Array` [`d6bca3a`](https://github.com/inspect-js/which-typed-array/commit/d6bca3a68ccfe33f6659a24b770068e89dab1592) +- [Dev Deps] update `jscs`, `nsp`, `eslint` [`f23b45b`](https://github.com/inspect-js/which-typed-array/commit/f23b45b2796bd1f63ddddf28b4b80b9709478cb3) +- [Dev Deps] update `@ljharb/eslint-config`, `eslint`, `semver`, `tape` [`ddb4484`](https://github.com/inspect-js/which-typed-array/commit/ddb4484adc3b45c4396632611556055f3b2f5990) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `is-callable`, `replace`, `semver`, `tape` [`4524e59`](https://github.com/inspect-js/which-typed-array/commit/4524e593e9387c185d5632696c62c1600c0b380f) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`1ec7056`](https://github.com/inspect-js/which-typed-array/commit/1ec70568565c479a6168b03e0a5aec6ec9ac5a21) +- [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` [`799487d`](https://github.com/inspect-js/which-typed-array/commit/799487d666b32d1ae0d27cfededf2f5480c5faea) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`8092598`](https://github.com/inspect-js/which-typed-array/commit/8092598998a1f9f8005b4e3d299eb09c96fa2e21) +- [Tests] up to `node` `v11.10` [`a5aabb1`](https://github.com/inspect-js/which-typed-array/commit/a5aabb1910e8408f857a791253487824c7c758d3) +- [Dev Deps] update `@ljharb/eslint-config`, `eslint`, `nsp`, `semver`, `tape` [`277be33`](https://github.com/inspect-js/which-typed-array/commit/277be331d9f05ff95644d6bcd896547ca620cd8e) +- [Tests] use `npm audit` instead of `nsp` [`ee97dc7`](https://github.com/inspect-js/which-typed-array/commit/ee97dc7c5d384d68f60ce6cb5a85d9509e75f72b) +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config` [`262ffb0`](https://github.com/inspect-js/which-typed-array/commit/262ffb025facb0795b33fbd5131183bdbc0a40f6) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`d6bbcfc`](https://github.com/inspect-js/which-typed-array/commit/d6bbcfc3eea427f0156fbdcf9ae11dbf3745a755) +- [Tests] up to `node` `v6.2` [`2ff89eb`](https://github.com/inspect-js/which-typed-array/commit/2ff89eb91754146c0bc1ae689f37458d84f6e690) +- Only apps should have lockfiles [`e2bc271`](https://github.com/inspect-js/which-typed-array/commit/e2bc271e1e9a6481a2836f892177825a808c331c) +- [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` [`b79e93b`](https://github.com/inspect-js/which-typed-array/commit/b79e93bf15c871ce0ff24fa3ad61001707eea463) +- [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` [`016dbff`](https://github.com/inspect-js/which-typed-array/commit/016dbff8c49c32cda7ec80d86006c8a7c43bc40c) +- [Dev Deps] update `eslint`, `tape` [`6ce4bbc`](https://github.com/inspect-js/which-typed-array/commit/6ce4bbc5f6caf632cbcf9ababbfe36e1bf4093d7) +- [Tests] on `node` `v10.1` [`f0683a0`](https://github.com/inspect-js/which-typed-array/commit/f0683a0c17e039e926ecaad4c4c341cd8e5878f1) +- [Tests] up to `node` `v7.2` [`2f29cef`](https://github.com/inspect-js/which-typed-array/commit/2f29cef42d30f87259cd6687c25a79ae4651d0c9) +- [Dev Deps] update `replace` [`73b5ba6`](https://github.com/inspect-js/which-typed-array/commit/73b5ba6e87638d13553985977cab9d1bad33e242) +- [Deps] update `function-bind` [`c8a18c2`](https://github.com/inspect-js/which-typed-array/commit/c8a18c2982e6b126ecc1d4655ec2e53b05535b20) +- [Tests] on `node` `v5.12` [`812102b`](https://github.com/inspect-js/which-typed-array/commit/812102bf223422da8f7a89e5a1308214dd158571) +- [Tests] on `node` `v5.10` [`271584f`](https://github.com/inspect-js/which-typed-array/commit/271584f3a8b10ef68a7d419ac0062b444e63d07c) + +## [v1.0.1](https://github.com/inspect-js/which-typed-array/compare/v1.0.0...v1.0.1) - 2016-03-19 + +### Commits + +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `is-callable` [`4a628c5`](https://github.com/inspect-js/which-typed-array/commit/4a628c520d8e080a9fa7e8218947d3b2ceedca72) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `is-callable` [`8e09372`](https://github.com/inspect-js/which-typed-array/commit/8e09372ded877a191cbf777060483227d5071e84) +- [Tests] up to `node` `v5.6`, `v4.3` [`3a35bf9`](https://github.com/inspect-js/which-typed-array/commit/3a35bf9fb9c7f8e6ac1b579ed2754087351ad1a5) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`9410d5e`](https://github.com/inspect-js/which-typed-array/commit/9410d5e35db4b834827b31ea1723bbeebbcde5ba) +- [Fix] `Symbol.toStringTag` is on the super-[[Prototype]] of Float32Array, not the [[Prototype]]. [`7c40a3a`](https://github.com/inspect-js/which-typed-array/commit/7c40a3a05046bbbd188340fb19471ad913e4af05) +- [Tests] up to `node` `v5.9`, `v4.4` [`07878e7`](https://github.com/inspect-js/which-typed-array/commit/07878e7cd23d586ddb9e85a03f675e0a574db246) +- Use the object form of "author" in package.json [`65caa56`](https://github.com/inspect-js/which-typed-array/commit/65caa560d1c0c15c1080b25a9df55c7373c73f08) +- [Tests] use pretest/posttest for linting/security [`c170f7e`](https://github.com/inspect-js/which-typed-array/commit/c170f7ebcf07475d6420f2d2d2d08b1646280cd4) +- [Deps] update `is-typed-array` [`9ab324e`](https://github.com/inspect-js/which-typed-array/commit/9ab324e746a7552b2d9363777fc5c9f5c2e31ce7) +- [Deps] update `function-bind` [`a723142`](https://github.com/inspect-js/which-typed-array/commit/a723142c70a5b6a4f8f5feecc9705619590f4eeb) +- [Deps] update `is-typed-array` [`ed82ce4`](https://github.com/inspect-js/which-typed-array/commit/ed82ce4e8ecc657fc6e839d23ef6347497bc93be) +- [Tests] on `node` `v4.2` [`f581c20`](https://github.com/inspect-js/which-typed-array/commit/f581c2031990668894a8e5a08eaf01a2548e822c) + +## v1.0.0 - 2015-10-05 + +### Commits + +- Dotfiles / Makefile [`667f89a`](https://github.com/inspect-js/which-typed-array/commit/667f89a9046502594e2559dbf5568e062af3b770) +- Tests. [`a14d05e`](https://github.com/inspect-js/which-typed-array/commit/a14d05ef443d2ac678cb0567befc0abf8cf21709) +- package.json [`560b1aa`](https://github.com/inspect-js/which-typed-array/commit/560b1aa4f8bbc5d41d9cee96c93faf08c25be0e5) +- Read me [`a22096e`](https://github.com/inspect-js/which-typed-array/commit/a22096e05773f93b34e672d3f743ec6f1963bc24) +- Implementation [`0b1ae28`](https://github.com/inspect-js/which-typed-array/commit/0b1ae2848372f6256cf075d687e3722878e67aca) +- Initial commit [`4b32f0a`](https://github.com/inspect-js/which-typed-array/commit/4b32f0a9d32165d6ab91797d6971ea83cf4ce9da) diff --git a/node_modules/which-typed-array/LICENSE b/node_modules/which-typed-array/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/node_modules/which-typed-array/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 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/which-typed-array/README.md b/node_modules/which-typed-array/README.md new file mode 100644 index 0000000..1b922cd --- /dev/null +++ b/node_modules/which-typed-array/README.md @@ -0,0 +1,70 @@ +# which-typed-array [![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] + +Which kind of Typed Array is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag. + +## Example + +```js +var whichTypedArray = require('which-typed-array'); +var assert = require('assert'); + +assert.equal(false, whichTypedArray(undefined)); +assert.equal(false, whichTypedArray(null)); +assert.equal(false, whichTypedArray(false)); +assert.equal(false, whichTypedArray(true)); +assert.equal(false, whichTypedArray([])); +assert.equal(false, whichTypedArray({})); +assert.equal(false, whichTypedArray(/a/g)); +assert.equal(false, whichTypedArray(new RegExp('a', 'g'))); +assert.equal(false, whichTypedArray(new Date())); +assert.equal(false, whichTypedArray(42)); +assert.equal(false, whichTypedArray(NaN)); +assert.equal(false, whichTypedArray(Infinity)); +assert.equal(false, whichTypedArray(new Number(42))); +assert.equal(false, whichTypedArray('foo')); +assert.equal(false, whichTypedArray(Object('foo'))); +assert.equal(false, whichTypedArray(function () {})); +assert.equal(false, whichTypedArray(function* () {})); +assert.equal(false, whichTypedArray(x => x * x)); +assert.equal(false, whichTypedArray([])); + +assert.equal('Int8Array', whichTypedArray(new Int8Array())); +assert.equal('Uint8Array', whichTypedArray(new Uint8Array())); +assert.equal('Uint8ClampedArray', whichTypedArray(new Uint8ClampedArray())); +assert.equal('Int16Array', whichTypedArray(new Int16Array())); +assert.equal('Uint16Array', whichTypedArray(new Uint16Array())); +assert.equal('Int32Array', whichTypedArray(new Int32Array())); +assert.equal('Uint32Array', whichTypedArray(new Uint32Array())); +assert.equal('Float32Array', whichTypedArray(new Float32Array())); +assert.equal('Float64Array', whichTypedArray(new Float64Array())); +assert.equal('BigInt64Array', whichTypedArray(new BigInt64Array())); +assert.equal('BigUint64Array', whichTypedArray(new BigUint64Array())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/which-typed-array +[npm-version-svg]: https://versionbadg.es/inspect-js/which-typed-array.svg +[deps-svg]: https://david-dm.org/inspect-js/which-typed-array.svg +[deps-url]: https://david-dm.org/inspect-js/which-typed-array +[dev-deps-svg]: https://david-dm.org/inspect-js/which-typed-array/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/which-typed-array#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/which-typed-array.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/which-typed-array.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/which-typed-array.svg +[downloads-url]: https://npm-stat.com/charts.html?package=which-typed-array +[codecov-image]: https://codecov.io/gh/inspect-js/which-typed-array/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/which-typed-array/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/which-typed-array +[actions-url]: https://github.com/inspect-js/which-typed-array/actions diff --git a/node_modules/which-typed-array/index.js b/node_modules/which-typed-array/index.js new file mode 100644 index 0000000..42080be --- /dev/null +++ b/node_modules/which-typed-array/index.js @@ -0,0 +1,55 @@ +'use strict'; + +var forEach = require('for-each'); +var availableTypedArrays = require('available-typed-arrays'); +var callBound = require('call-bind/callBound'); +var gOPD = require('gopd'); + +var $toString = callBound('Object.prototype.toString'); +var hasToStringTag = require('has-tostringtag/shams')(); + +var g = typeof globalThis === 'undefined' ? global : globalThis; +var typedArrays = availableTypedArrays(); + +var $slice = callBound('String.prototype.slice'); +var toStrTags = {}; +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + if (typeof g[typedArray] === 'function') { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + descriptor = gOPD(superProto, Symbol.toStringTag); + } + toStrTags[typedArray] = descriptor.get; + } + } + }); +} + +var tryTypedArrays = function tryAllTypedArrays(value) { + var foundName = false; + forEach(toStrTags, function (getter, typedArray) { + if (!foundName) { + try { + var name = getter.call(value); + if (name === typedArray) { + foundName = name; + } + } catch (e) {} + } + }); + return foundName; +}; + +var isTypedArray = require('is-typed-array'); + +module.exports = function whichTypedArray(value) { + if (!isTypedArray(value)) { return false; } + if (!hasToStringTag || !(Symbol.toStringTag in value)) { return $slice($toString(value), 8, -1); } + return tryTypedArrays(value); +}; diff --git a/node_modules/which-typed-array/package.json b/node_modules/which-typed-array/package.json new file mode 100644 index 0000000..c717f99 --- /dev/null +++ b/node_modules/which-typed-array/package.json @@ -0,0 +1,116 @@ +{ + "name": "which-typed-array", + "version": "1.1.9", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "Which kind of Typed Array is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag.", + "license": "MIT", + "main": "index.js", + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only && npm run test:harmony", + "tests-only": "nyc tape test", + "test:harmony": "nyc node --harmony --es-staging test", + "posttest": "aud --production", + "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/which-typed-array.git" + }, + "keywords": [ + "array", + "TypedArray", + "typed array", + "which", + "typed", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", + "ES6", + "toStringTag", + "Symbol.toStringTag", + "@@toStringTag" + ], + "dependencies": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0", + "is-typed-array": "^1.1.10" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.1", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "is-callable": "^1.2.7", + "make-arrow-function": "^1.2.0", + "make-generator-function": "^2.0.0", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.1" + }, + "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 + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/which-typed-array/test/index.js b/node_modules/which-typed-array/test/index.js new file mode 100644 index 0000000..e6711b2 --- /dev/null +++ b/node_modules/which-typed-array/test/index.js @@ -0,0 +1,99 @@ +'use strict'; + +var test = require('tape'); +var whichTypedArray = require('../'); +var isCallable = require('is-callable'); +var hasToStringTag = require('has-tostringtag/shams')(); +var generators = require('make-generator-function')(); +var arrows = require('make-arrow-function').list(); +var forEach = require('for-each'); + +var typedArrayNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array' +]; + +test('not arrays', function (t) { + t.test('non-number/string primitives', function (st) { + st.equal(false, whichTypedArray(), 'undefined is not typed array'); + st.equal(false, whichTypedArray(null), 'null is not typed array'); + st.equal(false, whichTypedArray(false), 'false is not typed array'); + st.equal(false, whichTypedArray(true), 'true is not typed array'); + st.end(); + }); + + t.equal(false, whichTypedArray({}), 'object is not typed array'); + t.equal(false, whichTypedArray(/a/g), 'regex literal is not typed array'); + t.equal(false, whichTypedArray(new RegExp('a', 'g')), 'regex object is not typed array'); + t.equal(false, whichTypedArray(new Date()), 'new Date() is not typed array'); + + t.test('numbers', function (st) { + st.equal(false, whichTypedArray(42), 'number is not typed array'); + st.equal(false, whichTypedArray(Object(42)), 'number object is not typed array'); + st.equal(false, whichTypedArray(NaN), 'NaN is not typed array'); + st.equal(false, whichTypedArray(Infinity), 'Infinity is not typed array'); + st.end(); + }); + + t.test('strings', function (st) { + st.equal(false, whichTypedArray('foo'), 'string primitive is not typed array'); + st.equal(false, whichTypedArray(Object('foo')), 'string object is not typed array'); + st.end(); + }); + + t.end(); +}); + +test('Functions', function (t) { + t.equal(false, whichTypedArray(function () {}), 'function is not typed array'); + t.end(); +}); + +test('Generators', { skip: generators.length === 0 }, function (t) { + forEach(generators, function (genFn) { + t.equal(false, whichTypedArray(genFn), 'generator function ' + genFn + ' is not typed array'); + }); + t.end(); +}); + +test('Arrow functions', { skip: arrows.length === 0 }, function (t) { + forEach(arrows, function (arrowFn) { + t.equal(false, whichTypedArray(arrowFn), 'arrow function ' + arrowFn + ' is not typed array'); + }); + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + forEach(typedArrayNames, function (typedArray) { + if (typeof global[typedArray] === 'function') { + var fakeTypedArray = []; + fakeTypedArray[Symbol.toStringTag] = typedArray; + t.equal(false, whichTypedArray(fakeTypedArray), 'faked ' + typedArray + ' is not typed array'); + } else { + t.comment('# SKIP ' + typedArray + ' is not supported'); + } + }); + t.end(); +}); + +test('Typed Arrays', function (t) { + forEach(typedArrayNames, function (typedArray) { + var TypedArray = global[typedArray]; + if (isCallable(TypedArray)) { + var arr = new TypedArray(10); + t.equal(typedArray, whichTypedArray(arr), 'new ' + typedArray + '(10) is typed array of type ' + typedArray); + } else { + t.comment('# SKIP ' + typedArray + ' is not supported'); + } + }); + t.end(); +}); diff --git a/node_modules/which/CHANGELOG.md b/node_modules/which/CHANGELOG.md new file mode 100644 index 0000000..7fb1f20 --- /dev/null +++ b/node_modules/which/CHANGELOG.md @@ -0,0 +1,166 @@ +# Changes + + +## 2.0.2 + +* Rename bin to `node-which` + +## 2.0.1 + +* generate changelog and publish on version bump +* enforce 100% test coverage +* Promise interface + +## 2.0.0 + +* Parallel tests, modern JavaScript, and drop support for node < 8 + +## 1.3.1 + +* update deps +* update travis + +## v1.3.0 + +* Add nothrow option to which.sync +* update tap + +## v1.2.14 + +* appveyor: drop node 5 and 0.x +* travis-ci: add node 6, drop 0.x + +## v1.2.13 + +* test: Pass missing option to pass on windows +* update tap +* update isexe to 2.0.0 +* neveragain.tech pledge request + +## v1.2.12 + +* Removed unused require + +## v1.2.11 + +* Prevent changelog script from being included in package + +## v1.2.10 + +* Use env.PATH only, not env.Path + +## v1.2.9 + +* fix for paths starting with ../ +* Remove unused `is-absolute` module + +## v1.2.8 + +* bullet items in changelog that contain (but don't start with) # + +## v1.2.7 + +* strip 'update changelog' changelog entries out of changelog + +## v1.2.6 + +* make the changelog bulleted + +## v1.2.5 + +* make a changelog, and keep it up to date +* don't include tests in package +* Properly handle relative-path executables +* appveyor +* Attach error code to Not Found error +* Make tests pass on Windows + +## v1.2.4 + +* Fix typo + +## v1.2.3 + +* update isexe, fix regression in pathExt handling + +## v1.2.2 + +* update deps, use isexe module, test windows + +## v1.2.1 + +* Sometimes windows PATH entries are quoted +* Fixed a bug in the check for group and user mode bits. This bug was introduced during refactoring for supporting strict mode. +* doc cli + +## v1.2.0 + +* Add support for opt.all and -as cli flags +* test the bin +* update travis +* Allow checking for multiple programs in bin/which +* tap 2 + +## v1.1.2 + +* travis +* Refactored and fixed undefined error on Windows +* Support strict mode + +## v1.1.1 + +* test +g exes against secondary groups, if available +* Use windows exe semantics on cygwin & msys +* cwd should be first in path on win32, not last +* Handle lower-case 'env.Path' on Windows +* Update docs +* use single-quotes + +## v1.1.0 + +* Add tests, depend on is-absolute + +## v1.0.9 + +* which.js: root is allowed to execute files owned by anyone + +## v1.0.8 + +* don't use graceful-fs + +## v1.0.7 + +* add license to package.json + +## v1.0.6 + +* isc license + +## 1.0.5 + +* Awful typo + +## 1.0.4 + +* Test for path absoluteness properly +* win: Allow '' as a pathext if cmd has a . in it + +## 1.0.3 + +* Remove references to execPath +* Make `which.sync()` work on Windows by honoring the PATHEXT variable. +* Make `isExe()` always return true on Windows. +* MIT + +## 1.0.2 + +* Only files can be exes + +## 1.0.1 + +* Respect the PATHEXT env for win32 support +* should 0755 the bin +* binary +* guts +* package +* 1st diff --git a/node_modules/which/LICENSE b/node_modules/which/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/which/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/which/README.md b/node_modules/which/README.md new file mode 100644 index 0000000..cd83350 --- /dev/null +++ b/node_modules/which/README.md @@ -0,0 +1,54 @@ +# which + +Like the unix `which` utility. + +Finds the first instance of a specified executable in the PATH +environment variable. Does not cache the results, so `hash -r` is not +needed when the PATH changes. + +## USAGE + +```javascript +var which = require('which') + +// async usage +which('node', function (er, resolvedPath) { + // er is returned if no "node" is found on the PATH + // if it is found, then the absolute path to the exec is returned +}) + +// or promise +which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... }) + +// sync usage +// throws if not found +var resolved = which.sync('node') + +// if nothrow option is used, returns null if not found +resolved = which.sync('node', {nothrow: true}) + +// Pass options to override the PATH and PATHEXT environment vars. +which('node', { path: someOtherPath }, function (er, resolved) { + if (er) + throw er + console.log('found at %j', resolved) +}) +``` + +## CLI USAGE + +Same as the BSD `which(1)` binary. + +``` +usage: which [-as] program ... +``` + +## OPTIONS + +You may pass an options object as the second argument. + +- `path`: Use instead of the `PATH` environment variable. +- `pathExt`: Use instead of the `PATHEXT` environment variable. +- `all`: Return all matches, instead of just the first one. Note that + this means the function returns an array of strings instead of a + single string. diff --git a/node_modules/which/bin/node-which b/node_modules/which/bin/node-which new file mode 100755 index 0000000..7cee372 --- /dev/null +++ b/node_modules/which/bin/node-which @@ -0,0 +1,52 @@ +#!/usr/bin/env node +var which = require("../") +if (process.argv.length < 3) + usage() + +function usage () { + console.error('usage: which [-as] program ...') + process.exit(1) +} + +var all = false +var silent = false +var dashdash = false +var args = process.argv.slice(2).filter(function (arg) { + if (dashdash || !/^-/.test(arg)) + return true + + if (arg === '--') { + dashdash = true + return false + } + + var flags = arg.substr(1).split('') + for (var f = 0; f < flags.length; f++) { + var flag = flags[f] + switch (flag) { + case 's': + silent = true + break + case 'a': + all = true + break + default: + console.error('which: illegal option -- ' + flag) + usage() + } + } + return false +}) + +process.exit(args.reduce(function (pv, current) { + try { + var f = which.sync(current, { all: all }) + if (all) + f = f.join('\n') + if (!silent) + console.log(f) + return pv; + } catch (e) { + return 1; + } +}, 0)) diff --git a/node_modules/which/package.json b/node_modules/which/package.json new file mode 100644 index 0000000..97ad7fb --- /dev/null +++ b/node_modules/which/package.json @@ -0,0 +1,43 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me)", + "name": "which", + "description": "Like which(1) unix command. Find the first instance of an executable in the PATH.", + "version": "2.0.2", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-which.git" + }, + "main": "which.js", + "bin": { + "node-which": "./bin/node-which" + }, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "devDependencies": { + "mkdirp": "^0.5.0", + "rimraf": "^2.6.2", + "tap": "^14.6.9" + }, + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublish": "npm run changelog", + "prechangelog": "bash gen-changelog.sh", + "changelog": "git add CHANGELOG.md", + "postchangelog": "git commit -m 'update changelog - '${npm_package_version}", + "postpublish": "git push origin --follow-tags" + }, + "files": [ + "which.js", + "bin/node-which" + ], + "tap": { + "check-coverage": true + }, + "engines": { + "node": ">= 8" + } +} diff --git a/node_modules/which/which.js b/node_modules/which/which.js new file mode 100644 index 0000000..82afffd --- /dev/null +++ b/node_modules/which/which.js @@ -0,0 +1,125 @@ +const isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys' + +const path = require('path') +const COLON = isWindows ? ';' : ':' +const isexe = require('isexe') + +const getNotFoundError = (cmd) => + Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) + +const getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] + : ( + [ + // windows always checks the cwd first + ...(isWindows ? [process.cwd()] : []), + ...(opt.path || process.env.PATH || + /* istanbul ignore next: very unusual */ '').split(colon), + ] + ) + const pathExtExe = isWindows + ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' + : '' + const pathExt = isWindows ? pathExtExe.split(colon) : [''] + + if (isWindows) { + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift('') + } + + return { + pathEnv, + pathExt, + pathExtExe, + } +} + +const which = (cmd, opt, cb) => { + if (typeof opt === 'function') { + cb = opt + opt = {} + } + if (!opt) + opt = {} + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) + const found = [] + + const step = i => new Promise((resolve, reject) => { + if (i === pathEnv.length) + return opt.all && found.length ? resolve(found) + : reject(getNotFoundError(cmd)) + + const ppRaw = pathEnv[i] + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw + + const pCmd = path.join(pathPart, cmd) + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd + + resolve(subStep(p, i, 0)) + }) + + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i + 1)) + const ext = pathExt[ii] + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext) + else + return resolve(p + ext) + } + return resolve(subStep(p, i, ii + 1)) + }) + }) + + return cb ? step(0).then(res => cb(null, res), cb) : step(0) +} + +const whichSync = (cmd, opt) => { + opt = opt || {} + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) + const found = [] + + for (let i = 0; i < pathEnv.length; i ++) { + const ppRaw = pathEnv[i] + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw + + const pCmd = path.join(pathPart, cmd) + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd + + for (let j = 0; j < pathExt.length; j ++) { + const cur = p + pathExt[j] + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }) + if (is) { + if (opt.all) + found.push(cur) + else + return cur + } + } catch (ex) {} + } + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) +} + +module.exports = which +which.sync = whichSync diff --git a/node_modules/yocto-queue/index.d.ts b/node_modules/yocto-queue/index.d.ts new file mode 100644 index 0000000..9541986 --- /dev/null +++ b/node_modules/yocto-queue/index.d.ts @@ -0,0 +1,56 @@ +declare class Queue implements Iterable { + /** + The size of the queue. + */ + readonly size: number; + + /** + Tiny queue data structure. + + The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop, or use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow. + + @example + ``` + import Queue = require('yocto-queue'); + + const queue = new Queue(); + + queue.enqueue('🦄'); + queue.enqueue('🌈'); + + console.log(queue.size); + //=> 2 + + console.log(...queue); + //=> '🦄 🌈' + + console.log(queue.dequeue()); + //=> '🦄' + + console.log(queue.dequeue()); + //=> '🌈' + ``` + */ + constructor(); + + [Symbol.iterator](): IterableIterator; + + /** + Add a value to the queue. + */ + enqueue(value: ValueType): void; + + /** + Remove the next value in the queue. + + @returns The removed value or `undefined` if the queue is empty. + */ + dequeue(): ValueType | undefined; + + /** + Clear the queue. + */ + clear(): void; +} + +export = Queue; diff --git a/node_modules/yocto-queue/index.js b/node_modules/yocto-queue/index.js new file mode 100644 index 0000000..2f3e6dc --- /dev/null +++ b/node_modules/yocto-queue/index.js @@ -0,0 +1,68 @@ +class Node { + /// value; + /// next; + + constructor(value) { + this.value = value; + + // TODO: Remove this when targeting Node.js 12. + this.next = undefined; + } +} + +class Queue { + // TODO: Use private class fields when targeting Node.js 12. + // #_head; + // #_tail; + // #_size; + + constructor() { + this.clear(); + } + + enqueue(value) { + const node = new Node(value); + + if (this._head) { + this._tail.next = node; + this._tail = node; + } else { + this._head = node; + this._tail = node; + } + + this._size++; + } + + dequeue() { + const current = this._head; + if (!current) { + return; + } + + this._head = this._head.next; + this._size--; + return current.value; + } + + clear() { + this._head = undefined; + this._tail = undefined; + this._size = 0; + } + + get size() { + return this._size; + } + + * [Symbol.iterator]() { + let current = this._head; + + while (current) { + yield current.value; + current = current.next; + } + } +} + +module.exports = Queue; diff --git a/node_modules/yocto-queue/license b/node_modules/yocto-queue/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/yocto-queue/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://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/yocto-queue/package.json b/node_modules/yocto-queue/package.json new file mode 100644 index 0000000..71a9101 --- /dev/null +++ b/node_modules/yocto-queue/package.json @@ -0,0 +1,43 @@ +{ + "name": "yocto-queue", + "version": "0.1.0", + "description": "Tiny queue data structure", + "license": "MIT", + "repository": "sindresorhus/yocto-queue", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "queue", + "data", + "structure", + "algorithm", + "queues", + "queuing", + "list", + "array", + "linkedlist", + "fifo", + "enqueue", + "dequeue", + "data-structure" + ], + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.13.1", + "xo": "^0.35.0" + } +} diff --git a/node_modules/yocto-queue/readme.md b/node_modules/yocto-queue/readme.md new file mode 100644 index 0000000..c72fefc --- /dev/null +++ b/node_modules/yocto-queue/readme.md @@ -0,0 +1,64 @@ +# yocto-queue [![](https://badgen.net/bundlephobia/minzip/yocto-queue)](https://bundlephobia.com/result?p=yocto-queue) + +> Tiny queue data structure + +You should use this package instead of an array if you do a lot of `Array#push()` and `Array#shift()` on large arrays, since `Array#shift()` has [linear time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(N)%E2%80%94Linear%20Time) *O(n)* while `Queue#dequeue()` has [constant time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(1)%20%E2%80%94%20Constant%20Time) *O(1)*. That makes a huge difference for large arrays. + +> A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is an ordered list of elements where an element is inserted at the end of the queue and is removed from the front of the queue. A queue works based on the first-in, first-out ([FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics))) principle. + +## Install + +``` +$ npm install yocto-queue +``` + +## Usage + +```js +const Queue = require('yocto-queue'); + +const queue = new Queue(); + +queue.enqueue('🦄'); +queue.enqueue('🌈'); + +console.log(queue.size); +//=> 2 + +console.log(...queue); +//=> '🦄 🌈' + +console.log(queue.dequeue()); +//=> '🦄' + +console.log(queue.dequeue()); +//=> '🌈' +``` + +## API + +### `queue = new Queue()` + +The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop, or use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow. + +#### `.enqueue(value)` + +Add a value to the queue. + +#### `.dequeue()` + +Remove the next value in the queue. + +Returns the removed value or `undefined` if the queue is empty. + +#### `.clear()` + +Clear the queue. + +#### `.size` + +The size of the queue. + +## Related + +- [quick-lru](https://github.com/sindresorhus/quick-lru) - Simple “Least Recently Used” (LRU) cache diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..9deefd3 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,5209 @@ +{ + "name": "slots", + "version": "0.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "slots", + "version": "0.0.0", + "devDependencies": { + "imba": "^2.0.0-alpha.226", + "vite": "^3.2.5", + "vite-plugin-imba": "^0.10.1" + } + }, + "node_modules/@adobe/css-tools": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.0.1.tgz", + "integrity": "sha512-+u76oB43nOHrF4DDWRLWDCtci7f3QJoEBigemIdIeTi1ODqjx6Tad9NCVnPRwewWlKkVab5PlK8DCtPTyX7S8g==", + "dev": true, + "peer": true + }, + "node_modules/@antfu/install-pkg": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-0.1.1.tgz", + "integrity": "sha512-LyB/8+bSfa0DFGC06zpCEfs89/XoWZwws5ygEa5D+Xsm3OfI+aXQ86VgVG7Acyef+rSZ5HE7J8rrxzrQeM3PjQ==", + "dev": true, + "dependencies": { + "execa": "^5.1.1", + "find-up": "^5.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", + "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/highlight": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.19.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", + "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", + "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.18.6", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "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, + "peer": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "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, + "peer": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "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, + "peer": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "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": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true, + "peer": true + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.8.0" + } + }, + "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": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/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, + "peer": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/runtime": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.20.7.tgz", + "integrity": "sha512-UF0tvkUtxwAgZ5W/KrkHf0Rn0fdnLDU9ScxBrEVNUprE/MzirjK4MJUX1/BVDv00Sv8cljtukVK1aky++X1SjQ==", + "dev": true, + "peer": true, + "dependencies": { + "regenerator-runtime": "^0.13.11" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.15.18.tgz", + "integrity": "sha512-5GT+kcs2WVGjVs7+boataCkO5Fg0y4kCjzkB5bAip7H4jfnOS3dA6KPiww9W1OEKTKeAcUVhdZGvgI65OXmUnw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.15.18.tgz", + "integrity": "sha512-L4jVKS82XVhw2nvzLg/19ClLWg0y27ulRwuP7lcyL6AbUWB5aPglXY3M21mauDQMDfRLs8cQmeT03r/+X3cZYQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.3.1.tgz", + "integrity": "sha512-wlrznINZI5sMjwvUoLVk617ll/UYfGIZNxmbU+Pa7wmkL4vYzhV9R2pwVqUh4NWWuLQWkI8+8mOkxs//prKQ3g==", + "dev": true, + "peer": true, + "dependencies": { + "jest-get-type": "^29.2.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/schemas": { + "version": "29.0.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.0.0.tgz", + "integrity": "sha512-3Ab5HgYIIAnS0HjqJHQYZS+zXc4tUmTmBH3z83ajI6afXp8X3ZtdLX+nXx+I7LNkJD7uN9LAVhgnjDgZa2z0kA==", + "dev": true, + "peer": true, + "dependencies": { + "@sinclair/typebox": "^0.24.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/types": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.3.1.tgz", + "integrity": "sha512-d0S0jmmTpjnhCmNpApgX3jrUZgZ22ivKJRvL2lli5hpCRoNnp1f85r2/wpKfXuYu8E7Jjh1hGfhPyup1NM5AmA==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/schemas": "^29.0.0", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@rollup/pluginutils": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.1.tgz", + "integrity": "sha512-iKnFXr7NkdZAIHiIWE+BX5ULi/ucVFYWD6TbAV+rZctiRTY2PL6tsIKhoIOaoskiWAkgu+VsbXgUVDNLHf+InQ==", + "dev": true, + "dependencies": { + "estree-walker": "^2.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.24.51", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.24.51.tgz", + "integrity": "sha512-1P1OROm/rdubP5aFDSZQILU0vrLCJ4fvHt6EoqHEM+2D/G5MK3bIaymUKLit8Js9gbns5UyJnkP/TZROLw4tUA==", + "dev": true, + "peer": true + }, + "node_modules/@testing-library/dom": { + "version": "8.19.1", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-8.19.1.tgz", + "integrity": "sha512-P6iIPyYQ+qH8CvGauAqanhVnjrnRe0IZFSYCeGkSRW9q3u8bdVn2NPI+lasFyVsEQn1J/IFmp5Aax41+dAP9wg==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "^5.0.0", + "chalk": "^4.1.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.4.4", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@testing-library/jest-dom": { + "version": "5.16.5", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-5.16.5.tgz", + "integrity": "sha512-N5ixQ2qKpi5OLYfwQmUb/5mSV9LneAcaUfp32pn4yCnpb8r/Yz0pXFPck21dIicKmi+ta5WRAknkZCfA8refMA==", + "dev": true, + "peer": true, + "dependencies": { + "@adobe/css-tools": "^4.0.1", + "@babel/runtime": "^7.9.2", + "@types/testing-library__jest-dom": "^5.9.1", + "aria-query": "^5.0.0", + "chalk": "^3.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.5.6", + "lodash": "^4.17.15", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=8", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/@testing-library/jest-dom/node_modules/chalk": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", + "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "dev": true, + "peer": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.1.tgz", + "integrity": "sha512-XTIieEY+gvJ39ChLcB4If5zHtPxt3Syj5rgZR+e1ctpmK8NjPf0zFqsz4JpLJT0xla9GFDKjy8Cpu331nrmE1Q==", + "dev": true, + "peer": true + }, + "node_modules/@types/chai": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.4.tgz", + "integrity": "sha512-KnRanxnpfpjUTqTCXslZSEdLfXExwgNxYPdiO2WGUj8+HDjFi8R3k5RVKPeSCzLjCcshCAtVO2QBbVuAV4kTnw==", + "dev": true, + "peer": true + }, + "node_modules/@types/chai-subset": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.3.tgz", + "integrity": "sha512-frBecisrNGz+F4T6bcc+NLeolfiojh5FxW2klu669+8BARtyQv2C/GkNW6FUodVe4BroGMP/wER/YDGc7rEllw==", + "dev": true, + "peer": true, + "dependencies": { + "@types/chai": "*" + } + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz", + "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==", + "dev": true, + "peer": true + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", + "dev": true, + "peer": true, + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", + "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", + "dev": true, + "peer": true, + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/jest": { + "version": "29.2.5", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.2.5.tgz", + "integrity": "sha512-H2cSxkKgVmqNHXP7TC2L/WUorrZu8ZigyRywfVzv6EyBlxj39n4C00hjXYQWsbwqgElaj/CiAeSRmk5GoaKTgw==", + "dev": true, + "peer": true, + "dependencies": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + } + }, + "node_modules/@types/jest/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@types/jest/node_modules/pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@types/jest/node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + }, + "node_modules/@types/node": { + "version": "18.11.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz", + "integrity": "sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==", + "dev": true, + "peer": true + }, + "node_modules/@types/stack-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", + "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", + "dev": true, + "peer": true + }, + "node_modules/@types/testing-library__jest-dom": { + "version": "5.14.5", + "resolved": "https://registry.npmjs.org/@types/testing-library__jest-dom/-/testing-library__jest-dom-5.14.5.tgz", + "integrity": "sha512-SBwbxYoyPIvxHbeHxTZX2Pe/74F/tX2/D3mMvzabdeJ25bBojfW0TyB8BHrbq/9zaaKICJZjLP+8r6AeZMFCuQ==", + "dev": true, + "peer": true, + "dependencies": { + "@types/jest": "*" + } + }, + "node_modules/@types/yargs": { + "version": "17.0.19", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.19.tgz", + "integrity": "sha512-cAx3qamwaYX9R0fzOIZAlFpo4A+1uBVCxqpKz9D26uTF4srRXaGTTsikQmaotCtNdbhzyUH7ft6p9ktz9s6UNQ==", + "dev": true, + "peer": true, + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==", + "dev": true, + "peer": true + }, + "node_modules/acorn": { + "version": "8.8.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.1.tgz", + "integrity": "sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA==", + "dev": true, + "peer": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", + "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "peer": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/aria-query": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.1.3.tgz", + "integrity": "sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==", + "dev": true, + "peer": true, + "dependencies": { + "deep-equal": "^2.0.5" + } + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "peer": true, + "engines": { + "node": "*" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz", + "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "peer": true + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "peer": true, + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chai": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.7.tgz", + "integrity": "sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==", + "dev": true, + "peer": true, + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^4.1.2", + "get-func-name": "^2.0.0", + "loupe": "^2.3.1", + "pathval": "^1.1.1", + "type-detect": "^4.0.5" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "peer": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/check-error": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", + "integrity": "sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==", + "dev": true, + "peer": true, + "engines": { + "node": "*" + } + }, + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "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" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/ci-info": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.7.1.tgz", + "integrity": "sha512-4jYS4MOAaCIStSRwiuxc4B8MYhIe676yO1sYGzARnjXkWpmzZMMYxY6zu8WYWDhSuth5zhrQ1rhNSibyyvv4/w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "peer": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "peer": true + }, + "node_modules/colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "dev": true, + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/cross-env": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", + "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.1" + }, + "bin": { + "cross-env": "src/bin/cross-env.js", + "cross-env-shell": "src/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=10.14", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "peer": true + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "dev": true, + "peer": true, + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/deep-equal": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.0.tgz", + "integrity": "sha512-RdpzE0Hv4lhowpIUKKMJfeH6C1pXdtT1/it80ubgWqwI3qpuxUBpC1S4hnHg+zjnuOoDkzUtUCEEkG+XG5l3Mw==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "es-get-iterator": "^1.1.2", + "get-intrinsic": "^1.1.3", + "is-arguments": "^1.1.1", + "is-array-buffer": "^3.0.1", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "isarray": "^2.0.5", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.4.3", + "side-channel": "^1.0.4", + "which-boxed-primitive": "^1.0.2", + "which-collection": "^1.0.1", + "which-typed-array": "^1.1.9" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/define-properties": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.4.tgz", + "integrity": "sha512-uckOqKcfaVvtBdsVkdPv3XjveQJsNQqmhXgRi8uhvWWuPYZCNlzT8qAyblUgNoXdHdjMTzAqeGjAoli8f+bzPA==", + "dev": true, + "peer": true, + "dependencies": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/diff": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.1.0.tgz", + "integrity": "sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw==", + "dev": true, + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/diff-sequences": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.3.1.tgz", + "integrity": "sha512-hlM3QR272NXCi4pq+N4Kok4kOp6EsgOM3ZSpJI7Da3UAs+Ttsi8MRmB6trM/lhyzUxGfOgnpkHtgqm5Q/CTcfQ==", + "dev": true, + "peer": true, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/dom-accessibility-api": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.15.tgz", + "integrity": "sha512-8o+oVqLQZoruQPYy3uAAQtc6YbtSiRq5aPJBhJ82YTJRHvI6ofhYAkC81WmjFTnfUbqg6T3aCglIpU9p/5e7Cw==", + "dev": true, + "peer": true + }, + "node_modules/dotenv": { + "version": "16.0.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.3.tgz", + "integrity": "sha512-7GO6HghkA5fYG9TYnNxi14/7K9f5occMlp3zXAuSxn7CKCxt9xbNWG7yF8hTCSUchlfWSe3uLmlPfigevRItzQ==", + "dev": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/es-get-iterator": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.2.tgz", + "integrity": "sha512-+DTO8GYwbMCwbywjimwZMHp8AuYXOS2JZFWoi2AlPOS3ebnII9w/NLpNZtA7A0YLaVDw+O7KFCeoIV7OPvM7hQ==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.0", + "has-symbols": "^1.0.1", + "is-arguments": "^1.1.0", + "is-map": "^2.0.2", + "is-set": "^2.0.2", + "is-string": "^1.0.5", + "isarray": "^2.0.5" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/esbuild": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.15.18.tgz", + "integrity": "sha512-x/R72SmW3sSFRm5zrrIjAhCeQSAWoni3CmHEqfQrZIQTM3lVCdehdwuIqaOtfC2slvpdlLa62GYoN8SxT23m6Q==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/android-arm": "0.15.18", + "@esbuild/linux-loong64": "0.15.18", + "esbuild-android-64": "0.15.18", + "esbuild-android-arm64": "0.15.18", + "esbuild-darwin-64": "0.15.18", + "esbuild-darwin-arm64": "0.15.18", + "esbuild-freebsd-64": "0.15.18", + "esbuild-freebsd-arm64": "0.15.18", + "esbuild-linux-32": "0.15.18", + "esbuild-linux-64": "0.15.18", + "esbuild-linux-arm": "0.15.18", + "esbuild-linux-arm64": "0.15.18", + "esbuild-linux-mips64le": "0.15.18", + "esbuild-linux-ppc64le": "0.15.18", + "esbuild-linux-riscv64": "0.15.18", + "esbuild-linux-s390x": "0.15.18", + "esbuild-netbsd-64": "0.15.18", + "esbuild-openbsd-64": "0.15.18", + "esbuild-sunos-64": "0.15.18", + "esbuild-windows-32": "0.15.18", + "esbuild-windows-64": "0.15.18", + "esbuild-windows-arm64": "0.15.18" + } + }, + "node_modules/esbuild-android-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-android-64/-/esbuild-android-64-0.15.18.tgz", + "integrity": "sha512-wnpt3OXRhcjfIDSZu9bnzT4/TNTDsOUvip0foZOUBG7QbSt//w3QV4FInVJxNhKc/ErhUxc5z4QjHtMi7/TbgA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-android-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.15.18.tgz", + "integrity": "sha512-G4xu89B8FCzav9XU8EjsXacCKSG2FT7wW9J6hOc18soEHJdtWu03L3TQDGf0geNxfLTtxENKBzMSq9LlbjS8OQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-darwin-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.15.18.tgz", + "integrity": "sha512-2WAvs95uPnVJPuYKP0Eqx+Dl/jaYseZEUUT1sjg97TJa4oBtbAKnPnl3b5M9l51/nbx7+QAEtuummJZW0sBEmg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-darwin-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.15.18.tgz", + "integrity": "sha512-tKPSxcTJ5OmNb1btVikATJ8NftlyNlc8BVNtyT/UAr62JFOhwHlnoPrhYWz09akBLHI9nElFVfWSTSRsrZiDUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-freebsd-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.15.18.tgz", + "integrity": "sha512-TT3uBUxkteAjR1QbsmvSsjpKjOX6UkCstr8nMr+q7zi3NuZ1oIpa8U41Y8I8dJH2fJgdC3Dj3CXO5biLQpfdZA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-freebsd-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.15.18.tgz", + "integrity": "sha512-R/oVr+X3Tkh+S0+tL41wRMbdWtpWB8hEAMsOXDumSSa6qJR89U0S/PpLXrGF7Wk/JykfpWNokERUpCeHDl47wA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-32": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.15.18.tgz", + "integrity": "sha512-lphF3HiCSYtaa9p1DtXndiQEeQDKPl9eN/XNoBf2amEghugNuqXNZA/ZovthNE2aa4EN43WroO0B85xVSjYkbg==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.15.18.tgz", + "integrity": "sha512-hNSeP97IviD7oxLKFuii5sDPJ+QHeiFTFLoLm7NZQligur8poNOWGIgpQ7Qf8Balb69hptMZzyOBIPtY09GZYw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-arm": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.15.18.tgz", + "integrity": "sha512-UH779gstRblS4aoS2qpMl3wjg7U0j+ygu3GjIeTonCcN79ZvpPee12Qun3vcdxX+37O5LFxz39XeW2I9bybMVA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.15.18.tgz", + "integrity": "sha512-54qr8kg/6ilcxd+0V3h9rjT4qmjc0CccMVWrjOEM/pEcUzt8X62HfBSeZfT2ECpM7104mk4yfQXkosY8Quptug==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-mips64le": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.15.18.tgz", + "integrity": "sha512-Mk6Ppwzzz3YbMl/ZZL2P0q1tnYqh/trYZ1VfNP47C31yT0K8t9s7Z077QrDA/guU60tGNp2GOwCQnp+DYv7bxQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-ppc64le": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.15.18.tgz", + "integrity": "sha512-b0XkN4pL9WUulPTa/VKHx2wLCgvIAbgwABGnKMY19WhKZPT+8BxhZdqz6EgkqCLld7X5qiCY2F/bfpUUlnFZ9w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-riscv64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.15.18.tgz", + "integrity": "sha512-ba2COaoF5wL6VLZWn04k+ACZjZ6NYniMSQStodFKH/Pu6RxzQqzsmjR1t9QC89VYJxBeyVPTaHuBMCejl3O/xg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-s390x": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.15.18.tgz", + "integrity": "sha512-VbpGuXEl5FCs1wDVp93O8UIzl3ZrglgnSQ+Hu79g7hZu6te6/YHgVJxCM2SqfIila0J3k0csfnf8VD2W7u2kzQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-netbsd-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.15.18.tgz", + "integrity": "sha512-98ukeCdvdX7wr1vUYQzKo4kQ0N2p27H7I11maINv73fVEXt2kyh4K4m9f35U1K43Xc2QGXlzAw0K9yoU7JUjOg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-openbsd-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.15.18.tgz", + "integrity": "sha512-yK5NCcH31Uae076AyQAXeJzt/vxIo9+omZRKj1pauhk3ITuADzuOx5N2fdHrAKPxN+zH3w96uFKlY7yIn490xQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-sunos-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.15.18.tgz", + "integrity": "sha512-On22LLFlBeLNj/YF3FT+cXcyKPEI263nflYlAhz5crxtp3yRG1Ugfr7ITyxmCmjm4vbN/dGrb/B7w7U8yJR9yw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-windows-32": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.15.18.tgz", + "integrity": "sha512-o+eyLu2MjVny/nt+E0uPnBxYuJHBvho8vWsC2lV61A7wwTWC3jkN2w36jtA+yv1UgYkHRihPuQsL23hsCYGcOQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-windows-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.15.18.tgz", + "integrity": "sha512-qinug1iTTaIIrCorAUjR0fcBk24fjzEedFYhhispP8Oc7SFvs+XeW3YpAKiKp8dRpizl4YYAhxMjlftAMJiaUw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-windows-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.15.18.tgz", + "integrity": "sha512-q9bsYzegpZcLziq0zgUi5KqGVtfhjxGbnksaBFYmWLxeV/S1fK4OLdq2DFYnXcLMjlZw2L0jLsk1eGoB522WXQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/expect": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.3.1.tgz", + "integrity": "sha512-gGb1yTgU30Q0O/tQq+z30KBWv24ApkMgFUpvKBkyLUBL68Wv8dHdJxTBZFl/iT8K/bqDHvUYRH6IIN3rToopPA==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/expect-utils": "^29.3.1", + "jest-get-type": "^29.2.0", + "jest-matcher-utils": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/fill-range": { + "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, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "dev": true, + "peer": true, + "dependencies": { + "is-callable": "^1.1.3" + } + }, + "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": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "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 + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-func-name": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", + "integrity": "sha512-Hm0ixYtaSZ/V7C8FJrtZIuBBI+iSgL+1Aq82zSu8VQNB4S3Gk8e7Qs3VwBDJAhmRZcFqkl3tQu36g/Foh5I5ig==", + "dev": true, + "peer": true, + "engines": { + "node": "*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.3.tgz", + "integrity": "sha512-QJVz1Tj7MS099PevUG5jvnt9tSkXN8K14dxQlikJuPt4uD9hHAHjLyLBiLR5zELelBdD9QNRAXZzsJx0WaDL9A==", + "dev": true, + "peer": true, + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dev": true, + "peer": true, + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", + "dev": true, + "peer": true + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-bigints": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", + "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", + "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", + "dev": true, + "peer": true, + "dependencies": { + "get-intrinsic": "^1.1.1" + }, + "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==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "dev": true, + "peer": true, + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true, + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/imba": { + "version": "2.0.0-alpha.226", + "resolved": "https://registry.npmjs.org/imba/-/imba-2.0.0-alpha.226.tgz", + "integrity": "sha512-QAg+ztLE8nbIqzT76ggrlqFzxM+c/zYHHcCMyGNx6U02yq8VcD8aMdUJGlDyvvKoRj5hzzdh99t0bdt6LUuCTw==", + "dev": true, + "dependencies": { + "@antfu/install-pkg": "^0.1.1", + "chokidar": "^3.4.3", + "colors": "^1.4.0", + "cross-spawn": "^7.0.3", + "dotenv": "^16.0.3", + "esbuild": "^0.15.2", + "local-pkg": "^0.4.2", + "picocolors": "^1.0.0", + "prompts": "^2.4.2" + }, + "bin": { + "imba": "bin/imba", + "imbac": "bin/imbac" + }, + "engines": { + "node": ">=13.10.0" + }, + "peerDependencies": { + "@testing-library/dom": "*", + "@testing-library/jest-dom": "*", + "vite": "*", + "vite-node": "*", + "vite-plugin-imba": "*", + "vitest": "*" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-arguments": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.1.tgz", + "integrity": "sha512-ASfLknmY8Xa2XtB4wmbz13Wu202baeA18cJBCeCy0wXUHZF0IPyVEXqKEcd+t2fNSLLL1vC6k7lxZEojNbISXQ==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "is-typed-array": "^1.1.10" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", + "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "dev": true, + "peer": true, + "dependencies": { + "has-bigints": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "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==", + "dev": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-boolean-object": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", + "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", + "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "dev": true, + "peer": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-map": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.2.tgz", + "integrity": "sha512-cOZFQQozTha1f4MxLFzlgKYPTyj26picdZTx82hbc/Xf4K/tZOOXSCkMvU4pKioRXGDLJRn0GM7Upe7kR721yg==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", + "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", + "dev": true, + "peer": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regex": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.2.tgz", + "integrity": "sha512-+2cnTEZeY5z/iXGbLhPrOAaK/Mau5k5eXq9j14CpRTftq0pAJu2MwVRSZhyZWBzx3o6X795Lz6Bpb6R0GKf37g==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz", + "integrity": "sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-string": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", + "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "dev": true, + "peer": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", + "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "dev": true, + "peer": true, + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.10", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.10.tgz", + "integrity": "sha512-PJqgEHiWZvMpaFZ3uTc8kHPM4+4ADTlDniuQL7cU/UDA0Ql7F70yGfHph3cLNe+c9toaigv+DFzTJKhc2CtO6A==", + "dev": true, + "peer": true, + "dependencies": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.1.tgz", + "integrity": "sha512-NSBR4kH5oVj1Uwvv970ruUkCV7O1mzgVFO4/rev2cLRda9Tm9HrL70ZPut4rOHgY0FNrUu9BCbXA2sdQ+x0chA==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.2.tgz", + "integrity": "sha512-t2yVvttHkQktwnNNmBQ98AhENLdPUTDTE21uPqAQ0ARwQfGeQKRVS0NNurH7bTf7RrvcVn1OOge45CnBeHCSmg==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "peer": true + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "node_modules/jest-diff": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.3.1.tgz", + "integrity": "sha512-vU8vyiO7568tmin2lA3r2DP8oRvzhvRcD4DjpXc6uGveQodyk7CKLhQlCSiwgx3g0pFaE88/KLZ0yaTWMc4Uiw==", + "dev": true, + "peer": true, + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.3.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-diff/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/jest-diff/node_modules/pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-diff/node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + }, + "node_modules/jest-get-type": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.2.0.tgz", + "integrity": "sha512-uXNJlg8hKFEnDgFsrCjznB+sTxdkuqiCL6zMgA75qEbAJjJYTs9XPrvDctrEig2GDow22T/LvHgO57iJhXB/UA==", + "dev": true, + "peer": true, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.3.1.tgz", + "integrity": "sha512-fkRMZUAScup3txIKfMe3AIZZmPEjWEdsPJFK3AIy5qRohWqQFg1qrmKfYXR9qEkNc7OdAu2N4KPHibEmy4HPeQ==", + "dev": true, + "peer": true, + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.3.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/jest-matcher-utils/node_modules/pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils/node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + }, + "node_modules/jest-message-util": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.3.1.tgz", + "integrity": "sha512-lMJTbgNcDm5z+6KDxWtqOFWlGQxD6XaYwBqHR8kmpkP+WWWG90I35kdtQHY67Ay5CSuydkTBbJG+tH9JShFCyA==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.3.1", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/jest-message-util/node_modules/pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util/node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + }, + "node_modules/jest-util": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.3.1.tgz", + "integrity": "sha512-7YOVZaiX7RJLv76ZfHt4nbNEzzTRiMW/IiOG7ZOKmTXmoGBxUDefgMAxQubu6WPVqP5zSzAdZG0FfLcC7HOIFQ==", + "dev": true, + "peer": true, + "dependencies": { + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "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, + "peer": true + }, + "node_modules/jsonc-parser": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.0.tgz", + "integrity": "sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==", + "dev": true, + "peer": true + }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/local-pkg": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.4.2.tgz", + "integrity": "sha512-mlERgSPrbxU3BP4qBqAvvwlgW4MTg78iwJdGGnv7kibKjWcJksrG3t6LB5lXI93wXRDvG4NpUgJFmTG4T6rdrg==", + "dev": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true, + "peer": true + }, + "node_modules/loupe": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", + "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", + "dev": true, + "peer": true, + "dependencies": { + "get-func-name": "^2.0.0" + } + }, + "node_modules/lz-string": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.4.4.tgz", + "integrity": "sha512-0ckx7ZHRPqb0oUm8zNr+90mtf9DQB60H1wMCjBtfi62Kl3a7JbHob6gA2bC+xRvZoOL+1hzUK8jeuEIQE8svEQ==", + "dev": true, + "peer": true, + "bin": { + "lz-string": "bin/bin.js" + } + }, + "node_modules/magic-string": { + "version": "0.26.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.26.7.tgz", + "integrity": "sha512-hX9XH3ziStPoPhJxLq1syWuZMxbDvGNbVchfrdCtanC7D13888bMFow61x8axrx+GfHLtVeAx2kxL7tTGRl+Ow==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.8" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "peer": true, + "dependencies": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/mlly": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.1.0.tgz", + "integrity": "sha512-cwzBrBfwGC1gYJyfcy8TcZU1f+dbH/T+TuOhtYP2wLv/Fb51/uV7HJQfBPtEupZ2ORLRU1EKFS/QfS3eo9+kBQ==", + "dev": true, + "peer": true, + "dependencies": { + "acorn": "^8.8.1", + "pathe": "^1.0.0", + "pkg-types": "^1.0.1", + "ufo": "^1.0.1" + } + }, + "node_modules/mlly/node_modules/pathe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.0.0.tgz", + "integrity": "sha512-nPdMG0Pd09HuSsr7QOKUXO2Jr9eqaDiZvDwdyIhNG5SHYujkQHYKDfGQkulBxvbDHz8oHLsTgKN86LSwYzSHAg==", + "dev": true, + "peer": true + }, + "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 + }, + "node_modules/nanoid": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", + "integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==", + "dev": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/object-inspect": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.2.tgz", + "integrity": "sha512-z+cPxW0QGUp0mcqcsgQyLVRDoXFQbXOwBaqyF7VIgI4TWNQsDHrBpUQslRmIfAoYWdYzs6UlKJtB2XJpTaNSpQ==", + "dev": true, + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-is": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", + "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", + "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/pathe": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-0.2.0.tgz", + "integrity": "sha512-sTitTPYnn23esFR3RlqYBWn4c45WGeLcsKzQiUpXJAyfcWkolvlYpV8FLo7JishK946oQwMFUCHXQ9AjGPKExw==", + "dev": true, + "peer": true + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "peer": true, + "engines": { + "node": "*" + } + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkg-types": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.0.1.tgz", + "integrity": "sha512-jHv9HB+Ho7dj6ItwppRDDl0iZRYBD0jsakHXtFgoLr+cHSF6xC+QL54sJmWxyGxOLYSHm0afhXhXcQDQqH9z8g==", + "dev": true, + "peer": true, + "dependencies": { + "jsonc-parser": "^3.2.0", + "mlly": "^1.0.0", + "pathe": "^1.0.0" + } + }, + "node_modules/pkg-types/node_modules/pathe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.0.0.tgz", + "integrity": "sha512-nPdMG0Pd09HuSsr7QOKUXO2Jr9eqaDiZvDwdyIhNG5SHYujkQHYKDfGQkulBxvbDHz8oHLsTgKN86LSwYzSHAg==", + "dev": true, + "peer": true + }, + "node_modules/postcss": { + "version": "8.4.21", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.21.tgz", + "integrity": "sha512-tP7u/Sn/dVxK2NnruI4H9BG+x+Wxz6oeZ1cJ8P6G/PZY0IKk4k/63TDsQf2kQq3+qoJeLm2kIBUNlZe3zgb4Zg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + } + ], + "dependencies": { + "nanoid": "^3.3.4", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "peer": true + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "dev": true, + "peer": true, + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", + "dev": true, + "peer": true + }, + "node_modules/regexp.prototype.flags": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.4.3.tgz", + "integrity": "sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "functions-have-names": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "dev": true, + "dependencies": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rollup": { + "version": "2.79.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.1.tgz", + "integrity": "sha512-uKxbd0IhMZOhjAiD5oAFp7BqvkA4Dv47qpOCtaNvng4HBwdbWtdOh8f5nZNuk2rp51PMGk3bzfWu5oayNEuYnw==", + "dev": true, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=10.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dev": true, + "peer": true, + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", + "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "peer": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "deprecated": "Please use @jridgewell/sourcemap-codec instead", + "dev": true + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "dev": true, + "peer": true, + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "dev": true, + "peer": true, + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-literal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-1.0.0.tgz", + "integrity": "sha512-5o4LsH1lzBzO9UFH63AJ2ad2/S2AVx6NtjOcaz+VTT2h1RiRvbipW72z8M/lxEhcPHDBQwpDrnTF7sXy/7OwCQ==", + "dev": true, + "peer": true, + "dependencies": { + "acorn": "^8.8.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "peer": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tinybench": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.3.1.tgz", + "integrity": "sha512-hGYWYBMPr7p4g5IarQE7XhlyWveh1EKhy4wUBS1LrHXCKYgvz+4/jCqgmJqZxxldesn05vccrtME2RLLZNW7iA==", + "dev": true, + "peer": true + }, + "node_modules/tinypool": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-0.3.0.tgz", + "integrity": "sha512-NX5KeqHOBZU6Bc0xj9Vr5Szbb1j8tUHIeD18s41aDJaPeC5QTdEhK0SpdpUrZlj2nv5cctNcSjaKNanXlfcVEQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-1.0.2.tgz", + "integrity": "sha512-bSGlgwLBYf7PnUsQ6WOc6SJ3pGOcd+d8AA6EUnLDDM0kWEstC1JIlSZA3UNliDXhd9ABoS7hiRBDCu+XP/sf1Q==", + "dev": true, + "peer": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/to-regex-range": { + "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, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/ufo": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.0.1.tgz", + "integrity": "sha512-boAm74ubXHY7KJQZLlXrtMz52qFvpsbOxDcZOnw/Wf+LS4Mmyu7JxmzD4tDLtUQtmZECypJ0FrCz4QIe6dvKRA==", + "dev": true, + "peer": true + }, + "node_modules/vite": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-3.2.5.tgz", + "integrity": "sha512-4mVEpXpSOgrssFZAOmGIr85wPHKvaDAcXqxVxVRZhljkJOMZi1ibLibzjLHzJvcok8BMguLc7g1W6W/GqZbLdQ==", + "dev": true, + "dependencies": { + "esbuild": "^0.15.9", + "postcss": "^8.4.18", + "resolve": "^1.22.1", + "rollup": "^2.79.1" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "peerDependencies": { + "@types/node": ">= 14", + "less": "*", + "sass": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-0.27.0.tgz", + "integrity": "sha512-O1o9joT0qCGx5Om6W0VNLr7M00ttrnFlfZX2d+oxt2T9oZ9DvYSv8kDRhNJDVhAgNgUm3Tc0h/+jppNf3mVKbA==", + "dev": true, + "peer": true, + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.3.4", + "mlly": "^1.0.0", + "pathe": "^0.2.0", + "picocolors": "^1.0.0", + "source-map": "^0.6.1", + "source-map-support": "^0.5.21", + "vite": "^3.0.0 || ^4.0.0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": ">=v14.16.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/vite-plugin-imba": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/vite-plugin-imba/-/vite-plugin-imba-0.10.1.tgz", + "integrity": "sha512-L4YKjsg5h5PPJRmLFw/68beerBRzCGiSjCqe0Xxh1aavvcAL57ZgT+7Y2kvwG7rcFO1YBdWtJ/tyJEsMK7rEAg==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^4.2.1", + "cross-env": "^7.0.3", + "debug": "^4.3.4", + "deepmerge": "^4.2.2", + "diff": "^5.1.0", + "kleur": "^4.1.5", + "magic-string": "^0.26.2" + }, + "engines": { + "node": "^14.18.0 || >= 16" + }, + "peerDependencies": { + "diff-match-patch": "^1.0.5", + "imba": "*", + "vite": "^3.0.0" + }, + "peerDependenciesMeta": { + "diff-match-patch": { + "optional": true + } + } + }, + "node_modules/vite-plugin-imba/node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/vitest": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-0.27.0.tgz", + "integrity": "sha512-BnOa7T6CnXVC6UgcAsvFOZ2Dtvqkt+/Nl6CRgh4qVT70vElf65XwEL6zMRyTF+h2QXJziEkxYdrLo5WCxckMLQ==", + "dev": true, + "peer": true, + "dependencies": { + "@types/chai": "^4.3.4", + "@types/chai-subset": "^1.3.3", + "@types/node": "*", + "acorn": "^8.8.1", + "acorn-walk": "^8.2.0", + "cac": "^6.7.14", + "chai": "^4.3.7", + "debug": "^4.3.4", + "local-pkg": "^0.4.2", + "picocolors": "^1.0.0", + "source-map": "^0.6.1", + "strip-literal": "^1.0.0", + "tinybench": "^2.3.1", + "tinypool": "^0.3.0", + "tinyspy": "^1.0.2", + "vite": "^3.0.0 || ^4.0.0", + "vite-node": "0.27.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": ">=v14.16.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@vitest/browser": "*", + "@vitest/ui": "*", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "dev": true, + "peer": true, + "dependencies": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.1.tgz", + "integrity": "sha512-W8xeTUwaln8i3K/cY1nGXzdnVZlidBcagyNFtBdD5kxnb4TvGKR7FfSIS3mYpwWS1QUCutfKz8IY8RjftB0+1A==", + "dev": true, + "peer": true, + "dependencies": { + "is-map": "^2.0.1", + "is-set": "^2.0.1", + "is-weakmap": "^2.0.1", + "is-weakset": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.9.tgz", + "integrity": "sha512-w9c4xkx6mPidwp7180ckYWfMmvxpjlZuIudNtDf4N/tTAUB8VJbX25qZoAsrtGuYNnGw3pa0AXgbGKRB8/EceA==", + "dev": true, + "peer": true, + "dependencies": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0", + "is-typed-array": "^1.1.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + }, + "dependencies": { + "@adobe/css-tools": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.0.1.tgz", + "integrity": "sha512-+u76oB43nOHrF4DDWRLWDCtci7f3QJoEBigemIdIeTi1ODqjx6Tad9NCVnPRwewWlKkVab5PlK8DCtPTyX7S8g==", + "dev": true, + "peer": true + }, + "@antfu/install-pkg": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-0.1.1.tgz", + "integrity": "sha512-LyB/8+bSfa0DFGC06zpCEfs89/XoWZwws5ygEa5D+Xsm3OfI+aXQ86VgVG7Acyef+rSZ5HE7J8rrxzrQeM3PjQ==", + "dev": true, + "requires": { + "execa": "^5.1.1", + "find-up": "^5.0.0" + } + }, + "@babel/code-frame": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", + "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", + "dev": true, + "peer": true, + "requires": { + "@babel/highlight": "^7.18.6" + } + }, + "@babel/helper-validator-identifier": { + "version": "7.19.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", + "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "dev": true, + "peer": true + }, + "@babel/highlight": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", + "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "dev": true, + "peer": true, + "requires": { + "@babel/helper-validator-identifier": "^7.18.6", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "dependencies": { + "ansi-styles": { + "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, + "peer": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "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, + "peer": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "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, + "peer": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true, + "peer": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "peer": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "peer": true + }, + "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, + "peer": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "@babel/runtime": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.20.7.tgz", + "integrity": "sha512-UF0tvkUtxwAgZ5W/KrkHf0Rn0fdnLDU9ScxBrEVNUprE/MzirjK4MJUX1/BVDv00Sv8cljtukVK1aky++X1SjQ==", + "dev": true, + "peer": true, + "requires": { + "regenerator-runtime": "^0.13.11" + } + }, + "@esbuild/android-arm": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.15.18.tgz", + "integrity": "sha512-5GT+kcs2WVGjVs7+boataCkO5Fg0y4kCjzkB5bAip7H4jfnOS3dA6KPiww9W1OEKTKeAcUVhdZGvgI65OXmUnw==", + "dev": true, + "optional": true + }, + "@esbuild/linux-loong64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.15.18.tgz", + "integrity": "sha512-L4jVKS82XVhw2nvzLg/19ClLWg0y27ulRwuP7lcyL6AbUWB5aPglXY3M21mauDQMDfRLs8cQmeT03r/+X3cZYQ==", + "dev": true, + "optional": true + }, + "@jest/expect-utils": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.3.1.tgz", + "integrity": "sha512-wlrznINZI5sMjwvUoLVk617ll/UYfGIZNxmbU+Pa7wmkL4vYzhV9R2pwVqUh4NWWuLQWkI8+8mOkxs//prKQ3g==", + "dev": true, + "peer": true, + "requires": { + "jest-get-type": "^29.2.0" + } + }, + "@jest/schemas": { + "version": "29.0.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.0.0.tgz", + "integrity": "sha512-3Ab5HgYIIAnS0HjqJHQYZS+zXc4tUmTmBH3z83ajI6afXp8X3ZtdLX+nXx+I7LNkJD7uN9LAVhgnjDgZa2z0kA==", + "dev": true, + "peer": true, + "requires": { + "@sinclair/typebox": "^0.24.1" + } + }, + "@jest/types": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.3.1.tgz", + "integrity": "sha512-d0S0jmmTpjnhCmNpApgX3jrUZgZ22ivKJRvL2lli5hpCRoNnp1f85r2/wpKfXuYu8E7Jjh1hGfhPyup1NM5AmA==", + "dev": true, + "peer": true, + "requires": { + "@jest/schemas": "^29.0.0", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + } + }, + "@rollup/pluginutils": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.1.tgz", + "integrity": "sha512-iKnFXr7NkdZAIHiIWE+BX5ULi/ucVFYWD6TbAV+rZctiRTY2PL6tsIKhoIOaoskiWAkgu+VsbXgUVDNLHf+InQ==", + "dev": true, + "requires": { + "estree-walker": "^2.0.1", + "picomatch": "^2.2.2" + } + }, + "@sinclair/typebox": { + "version": "0.24.51", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.24.51.tgz", + "integrity": "sha512-1P1OROm/rdubP5aFDSZQILU0vrLCJ4fvHt6EoqHEM+2D/G5MK3bIaymUKLit8Js9gbns5UyJnkP/TZROLw4tUA==", + "dev": true, + "peer": true + }, + "@testing-library/dom": { + "version": "8.19.1", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-8.19.1.tgz", + "integrity": "sha512-P6iIPyYQ+qH8CvGauAqanhVnjrnRe0IZFSYCeGkSRW9q3u8bdVn2NPI+lasFyVsEQn1J/IFmp5Aax41+dAP9wg==", + "dev": true, + "peer": true, + "requires": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "^5.0.0", + "chalk": "^4.1.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.4.4", + "pretty-format": "^27.0.2" + } + }, + "@testing-library/jest-dom": { + "version": "5.16.5", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-5.16.5.tgz", + "integrity": "sha512-N5ixQ2qKpi5OLYfwQmUb/5mSV9LneAcaUfp32pn4yCnpb8r/Yz0pXFPck21dIicKmi+ta5WRAknkZCfA8refMA==", + "dev": true, + "peer": true, + "requires": { + "@adobe/css-tools": "^4.0.1", + "@babel/runtime": "^7.9.2", + "@types/testing-library__jest-dom": "^5.9.1", + "aria-query": "^5.0.0", + "chalk": "^3.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.5.6", + "lodash": "^4.17.15", + "redent": "^3.0.0" + }, + "dependencies": { + "chalk": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", + "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "dev": true, + "peer": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + } + } + }, + "@types/aria-query": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.1.tgz", + "integrity": "sha512-XTIieEY+gvJ39ChLcB4If5zHtPxt3Syj5rgZR+e1ctpmK8NjPf0zFqsz4JpLJT0xla9GFDKjy8Cpu331nrmE1Q==", + "dev": true, + "peer": true + }, + "@types/chai": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.4.tgz", + "integrity": "sha512-KnRanxnpfpjUTqTCXslZSEdLfXExwgNxYPdiO2WGUj8+HDjFi8R3k5RVKPeSCzLjCcshCAtVO2QBbVuAV4kTnw==", + "dev": true, + "peer": true + }, + "@types/chai-subset": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.3.tgz", + "integrity": "sha512-frBecisrNGz+F4T6bcc+NLeolfiojh5FxW2klu669+8BARtyQv2C/GkNW6FUodVe4BroGMP/wER/YDGc7rEllw==", + "dev": true, + "peer": true, + "requires": { + "@types/chai": "*" + } + }, + "@types/istanbul-lib-coverage": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz", + "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==", + "dev": true, + "peer": true + }, + "@types/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", + "dev": true, + "peer": true, + "requires": { + "@types/istanbul-lib-coverage": "*" + } + }, + "@types/istanbul-reports": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", + "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", + "dev": true, + "peer": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/jest": { + "version": "29.2.5", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.2.5.tgz", + "integrity": "sha512-H2cSxkKgVmqNHXP7TC2L/WUorrZu8ZigyRywfVzv6EyBlxj39n4C00hjXYQWsbwqgElaj/CiAeSRmk5GoaKTgw==", + "dev": true, + "peer": true, + "requires": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true + }, + "pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "requires": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + } + }, + "react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + } + } + }, + "@types/node": { + "version": "18.11.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz", + "integrity": "sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==", + "dev": true, + "peer": true + }, + "@types/stack-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", + "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", + "dev": true, + "peer": true + }, + "@types/testing-library__jest-dom": { + "version": "5.14.5", + "resolved": "https://registry.npmjs.org/@types/testing-library__jest-dom/-/testing-library__jest-dom-5.14.5.tgz", + "integrity": "sha512-SBwbxYoyPIvxHbeHxTZX2Pe/74F/tX2/D3mMvzabdeJ25bBojfW0TyB8BHrbq/9zaaKICJZjLP+8r6AeZMFCuQ==", + "dev": true, + "peer": true, + "requires": { + "@types/jest": "*" + } + }, + "@types/yargs": { + "version": "17.0.19", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.19.tgz", + "integrity": "sha512-cAx3qamwaYX9R0fzOIZAlFpo4A+1uBVCxqpKz9D26uTF4srRXaGTTsikQmaotCtNdbhzyUH7ft6p9ktz9s6UNQ==", + "dev": true, + "peer": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "@types/yargs-parser": { + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==", + "dev": true, + "peer": true + }, + "acorn": { + "version": "8.8.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.1.tgz", + "integrity": "sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA==", + "dev": true, + "peer": true + }, + "acorn-walk": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", + "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "dev": true, + "peer": true + }, + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "peer": true + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "peer": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "requires": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + } + }, + "aria-query": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.1.3.tgz", + "integrity": "sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==", + "dev": true, + "peer": true, + "requires": { + "deep-equal": "^2.0.5" + } + }, + "assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "peer": true + }, + "available-typed-arrays": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz", + "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==", + "dev": true, + "peer": true + }, + "binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "dev": true + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "requires": { + "fill-range": "^7.0.1" + } + }, + "buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "peer": true + }, + "cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "peer": true + }, + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "peer": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "chai": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.7.tgz", + "integrity": "sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==", + "dev": true, + "peer": true, + "requires": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.2", + "deep-eql": "^4.1.2", + "get-func-name": "^2.0.0", + "loupe": "^2.3.1", + "pathval": "^1.1.1", + "type-detect": "^4.0.5" + } + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "peer": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "check-error": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", + "integrity": "sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==", + "dev": true, + "peer": true + }, + "chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "dev": 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": "3.7.1", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.7.1.tgz", + "integrity": "sha512-4jYS4MOAaCIStSRwiuxc4B8MYhIe676yO1sYGzARnjXkWpmzZMMYxY6zu8WYWDhSuth5zhrQ1rhNSibyyvv4/w==", + "dev": true, + "peer": true + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "peer": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "peer": true + }, + "colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "dev": true + }, + "cross-env": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", + "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", + "dev": true, + "requires": { + "cross-spawn": "^7.0.1" + } + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "peer": true + }, + "debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "requires": { + "ms": "2.1.2" + } + }, + "deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "dev": true, + "peer": true, + "requires": { + "type-detect": "^4.0.0" + } + }, + "deep-equal": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.0.tgz", + "integrity": "sha512-RdpzE0Hv4lhowpIUKKMJfeH6C1pXdtT1/it80ubgWqwI3qpuxUBpC1S4hnHg+zjnuOoDkzUtUCEEkG+XG5l3Mw==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2", + "es-get-iterator": "^1.1.2", + "get-intrinsic": "^1.1.3", + "is-arguments": "^1.1.1", + "is-array-buffer": "^3.0.1", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "isarray": "^2.0.5", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.4.3", + "side-channel": "^1.0.4", + "which-boxed-primitive": "^1.0.2", + "which-collection": "^1.0.1", + "which-typed-array": "^1.1.9" + } + }, + "deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "dev": true + }, + "define-properties": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.4.tgz", + "integrity": "sha512-uckOqKcfaVvtBdsVkdPv3XjveQJsNQqmhXgRi8uhvWWuPYZCNlzT8qAyblUgNoXdHdjMTzAqeGjAoli8f+bzPA==", + "dev": true, + "peer": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, + "diff": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.1.0.tgz", + "integrity": "sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw==", + "dev": true + }, + "diff-sequences": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.3.1.tgz", + "integrity": "sha512-hlM3QR272NXCi4pq+N4Kok4kOp6EsgOM3ZSpJI7Da3UAs+Ttsi8MRmB6trM/lhyzUxGfOgnpkHtgqm5Q/CTcfQ==", + "dev": true, + "peer": true + }, + "dom-accessibility-api": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.15.tgz", + "integrity": "sha512-8o+oVqLQZoruQPYy3uAAQtc6YbtSiRq5aPJBhJ82YTJRHvI6ofhYAkC81WmjFTnfUbqg6T3aCglIpU9p/5e7Cw==", + "dev": true, + "peer": true + }, + "dotenv": { + "version": "16.0.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.3.tgz", + "integrity": "sha512-7GO6HghkA5fYG9TYnNxi14/7K9f5occMlp3zXAuSxn7CKCxt9xbNWG7yF8hTCSUchlfWSe3uLmlPfigevRItzQ==", + "dev": true + }, + "es-get-iterator": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.2.tgz", + "integrity": "sha512-+DTO8GYwbMCwbywjimwZMHp8AuYXOS2JZFWoi2AlPOS3ebnII9w/NLpNZtA7A0YLaVDw+O7KFCeoIV7OPvM7hQ==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.0", + "has-symbols": "^1.0.1", + "is-arguments": "^1.1.0", + "is-map": "^2.0.2", + "is-set": "^2.0.2", + "is-string": "^1.0.5", + "isarray": "^2.0.5" + } + }, + "esbuild": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.15.18.tgz", + "integrity": "sha512-x/R72SmW3sSFRm5zrrIjAhCeQSAWoni3CmHEqfQrZIQTM3lVCdehdwuIqaOtfC2slvpdlLa62GYoN8SxT23m6Q==", + "dev": true, + "requires": { + "@esbuild/android-arm": "0.15.18", + "@esbuild/linux-loong64": "0.15.18", + "esbuild-android-64": "0.15.18", + "esbuild-android-arm64": "0.15.18", + "esbuild-darwin-64": "0.15.18", + "esbuild-darwin-arm64": "0.15.18", + "esbuild-freebsd-64": "0.15.18", + "esbuild-freebsd-arm64": "0.15.18", + "esbuild-linux-32": "0.15.18", + "esbuild-linux-64": "0.15.18", + "esbuild-linux-arm": "0.15.18", + "esbuild-linux-arm64": "0.15.18", + "esbuild-linux-mips64le": "0.15.18", + "esbuild-linux-ppc64le": "0.15.18", + "esbuild-linux-riscv64": "0.15.18", + "esbuild-linux-s390x": "0.15.18", + "esbuild-netbsd-64": "0.15.18", + "esbuild-openbsd-64": "0.15.18", + "esbuild-sunos-64": "0.15.18", + "esbuild-windows-32": "0.15.18", + "esbuild-windows-64": "0.15.18", + "esbuild-windows-arm64": "0.15.18" + } + }, + "esbuild-android-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-android-64/-/esbuild-android-64-0.15.18.tgz", + "integrity": "sha512-wnpt3OXRhcjfIDSZu9bnzT4/TNTDsOUvip0foZOUBG7QbSt//w3QV4FInVJxNhKc/ErhUxc5z4QjHtMi7/TbgA==", + "dev": true, + "optional": true + }, + "esbuild-android-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.15.18.tgz", + "integrity": "sha512-G4xu89B8FCzav9XU8EjsXacCKSG2FT7wW9J6hOc18soEHJdtWu03L3TQDGf0geNxfLTtxENKBzMSq9LlbjS8OQ==", + "dev": true, + "optional": true + }, + "esbuild-darwin-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.15.18.tgz", + "integrity": "sha512-2WAvs95uPnVJPuYKP0Eqx+Dl/jaYseZEUUT1sjg97TJa4oBtbAKnPnl3b5M9l51/nbx7+QAEtuummJZW0sBEmg==", + "dev": true, + "optional": true + }, + "esbuild-darwin-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.15.18.tgz", + "integrity": "sha512-tKPSxcTJ5OmNb1btVikATJ8NftlyNlc8BVNtyT/UAr62JFOhwHlnoPrhYWz09akBLHI9nElFVfWSTSRsrZiDUA==", + "dev": true, + "optional": true + }, + "esbuild-freebsd-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.15.18.tgz", + "integrity": "sha512-TT3uBUxkteAjR1QbsmvSsjpKjOX6UkCstr8nMr+q7zi3NuZ1oIpa8U41Y8I8dJH2fJgdC3Dj3CXO5biLQpfdZA==", + "dev": true, + "optional": true + }, + "esbuild-freebsd-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.15.18.tgz", + "integrity": "sha512-R/oVr+X3Tkh+S0+tL41wRMbdWtpWB8hEAMsOXDumSSa6qJR89U0S/PpLXrGF7Wk/JykfpWNokERUpCeHDl47wA==", + "dev": true, + "optional": true + }, + "esbuild-linux-32": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.15.18.tgz", + "integrity": "sha512-lphF3HiCSYtaa9p1DtXndiQEeQDKPl9eN/XNoBf2amEghugNuqXNZA/ZovthNE2aa4EN43WroO0B85xVSjYkbg==", + "dev": true, + "optional": true + }, + "esbuild-linux-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.15.18.tgz", + "integrity": "sha512-hNSeP97IviD7oxLKFuii5sDPJ+QHeiFTFLoLm7NZQligur8poNOWGIgpQ7Qf8Balb69hptMZzyOBIPtY09GZYw==", + "dev": true, + "optional": true + }, + "esbuild-linux-arm": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.15.18.tgz", + "integrity": "sha512-UH779gstRblS4aoS2qpMl3wjg7U0j+ygu3GjIeTonCcN79ZvpPee12Qun3vcdxX+37O5LFxz39XeW2I9bybMVA==", + "dev": true, + "optional": true + }, + "esbuild-linux-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.15.18.tgz", + "integrity": "sha512-54qr8kg/6ilcxd+0V3h9rjT4qmjc0CccMVWrjOEM/pEcUzt8X62HfBSeZfT2ECpM7104mk4yfQXkosY8Quptug==", + "dev": true, + "optional": true + }, + "esbuild-linux-mips64le": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.15.18.tgz", + "integrity": "sha512-Mk6Ppwzzz3YbMl/ZZL2P0q1tnYqh/trYZ1VfNP47C31yT0K8t9s7Z077QrDA/guU60tGNp2GOwCQnp+DYv7bxQ==", + "dev": true, + "optional": true + }, + "esbuild-linux-ppc64le": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.15.18.tgz", + "integrity": "sha512-b0XkN4pL9WUulPTa/VKHx2wLCgvIAbgwABGnKMY19WhKZPT+8BxhZdqz6EgkqCLld7X5qiCY2F/bfpUUlnFZ9w==", + "dev": true, + "optional": true + }, + "esbuild-linux-riscv64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.15.18.tgz", + "integrity": "sha512-ba2COaoF5wL6VLZWn04k+ACZjZ6NYniMSQStodFKH/Pu6RxzQqzsmjR1t9QC89VYJxBeyVPTaHuBMCejl3O/xg==", + "dev": true, + "optional": true + }, + "esbuild-linux-s390x": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.15.18.tgz", + "integrity": "sha512-VbpGuXEl5FCs1wDVp93O8UIzl3ZrglgnSQ+Hu79g7hZu6te6/YHgVJxCM2SqfIila0J3k0csfnf8VD2W7u2kzQ==", + "dev": true, + "optional": true + }, + "esbuild-netbsd-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.15.18.tgz", + "integrity": "sha512-98ukeCdvdX7wr1vUYQzKo4kQ0N2p27H7I11maINv73fVEXt2kyh4K4m9f35U1K43Xc2QGXlzAw0K9yoU7JUjOg==", + "dev": true, + "optional": true + }, + "esbuild-openbsd-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.15.18.tgz", + "integrity": "sha512-yK5NCcH31Uae076AyQAXeJzt/vxIo9+omZRKj1pauhk3ITuADzuOx5N2fdHrAKPxN+zH3w96uFKlY7yIn490xQ==", + "dev": true, + "optional": true + }, + "esbuild-sunos-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.15.18.tgz", + "integrity": "sha512-On22LLFlBeLNj/YF3FT+cXcyKPEI263nflYlAhz5crxtp3yRG1Ugfr7ITyxmCmjm4vbN/dGrb/B7w7U8yJR9yw==", + "dev": true, + "optional": true + }, + "esbuild-windows-32": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.15.18.tgz", + "integrity": "sha512-o+eyLu2MjVny/nt+E0uPnBxYuJHBvho8vWsC2lV61A7wwTWC3jkN2w36jtA+yv1UgYkHRihPuQsL23hsCYGcOQ==", + "dev": true, + "optional": true + }, + "esbuild-windows-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.15.18.tgz", + "integrity": "sha512-qinug1iTTaIIrCorAUjR0fcBk24fjzEedFYhhispP8Oc7SFvs+XeW3YpAKiKp8dRpizl4YYAhxMjlftAMJiaUw==", + "dev": true, + "optional": true + }, + "esbuild-windows-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.15.18.tgz", + "integrity": "sha512-q9bsYzegpZcLziq0zgUi5KqGVtfhjxGbnksaBFYmWLxeV/S1fK4OLdq2DFYnXcLMjlZw2L0jLsk1eGoB522WXQ==", + "dev": true, + "optional": true + }, + "escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true, + "peer": true + }, + "estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true + }, + "execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "requires": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + } + }, + "expect": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.3.1.tgz", + "integrity": "sha512-gGb1yTgU30Q0O/tQq+z30KBWv24ApkMgFUpvKBkyLUBL68Wv8dHdJxTBZFl/iT8K/bqDHvUYRH6IIN3rToopPA==", + "dev": true, + "peer": true, + "requires": { + "@jest/expect-utils": "^29.3.1", + "jest-get-type": "^29.2.0", + "jest-matcher-utils": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1" + } + }, + "fill-range": { + "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, + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "requires": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + } + }, + "for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "dev": true, + "peer": true, + "requires": { + "is-callable": "^1.1.3" + } + }, + "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 + }, + "functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "peer": true + }, + "get-func-name": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", + "integrity": "sha512-Hm0ixYtaSZ/V7C8FJrtZIuBBI+iSgL+1Aq82zSu8VQNB4S3Gk8e7Qs3VwBDJAhmRZcFqkl3tQu36g/Foh5I5ig==", + "dev": true, + "peer": true + }, + "get-intrinsic": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.3.tgz", + "integrity": "sha512-QJVz1Tj7MS099PevUG5jvnt9tSkXN8K14dxQlikJuPt4uD9hHAHjLyLBiLR5zELelBdD9QNRAXZzsJx0WaDL9A==", + "dev": true, + "peer": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.3" + } + }, + "get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true + }, + "glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "requires": { + "is-glob": "^4.0.1" + } + }, + "gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dev": true, + "peer": true, + "requires": { + "get-intrinsic": "^1.1.3" + } + }, + "graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", + "dev": true, + "peer": true + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-bigints": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", + "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "dev": true, + "peer": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "peer": true + }, + "has-property-descriptors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", + "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", + "dev": true, + "peer": true, + "requires": { + "get-intrinsic": "^1.1.1" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true, + "peer": true + }, + "has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "dev": true, + "peer": true, + "requires": { + "has-symbols": "^1.0.2" + } + }, + "human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true + }, + "imba": { + "version": "2.0.0-alpha.226", + "resolved": "https://registry.npmjs.org/imba/-/imba-2.0.0-alpha.226.tgz", + "integrity": "sha512-QAg+ztLE8nbIqzT76ggrlqFzxM+c/zYHHcCMyGNx6U02yq8VcD8aMdUJGlDyvvKoRj5hzzdh99t0bdt6LUuCTw==", + "dev": true, + "requires": { + "@antfu/install-pkg": "^0.1.1", + "chokidar": "^3.4.3", + "colors": "^1.4.0", + "cross-spawn": "^7.0.3", + "dotenv": "^16.0.3", + "esbuild": "^0.15.2", + "local-pkg": "^0.4.2", + "picocolors": "^1.0.0", + "prompts": "^2.4.2" + } + }, + "indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "peer": true + }, + "is-arguments": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + } + }, + "is-array-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.1.tgz", + "integrity": "sha512-ASfLknmY8Xa2XtB4wmbz13Wu202baeA18cJBCeCy0wXUHZF0IPyVEXqKEcd+t2fNSLLL1vC6k7lxZEojNbISXQ==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "is-typed-array": "^1.1.10" + } + }, + "is-bigint": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", + "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "dev": true, + "peer": true, + "requires": { + "has-bigints": "^1.0.1" + } + }, + "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==", + "dev": true, + "requires": { + "binary-extensions": "^2.0.0" + } + }, + "is-boolean-object": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", + "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + } + }, + "is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "peer": true + }, + "is-core-module": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", + "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", + "dev": true, + "requires": { + "has": "^1.0.3" + } + }, + "is-date-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "dev": true, + "peer": true, + "requires": { + "has-tostringtag": "^1.0.0" + } + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true + }, + "is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-map": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.2.tgz", + "integrity": "sha512-cOZFQQozTha1f4MxLFzlgKYPTyj26picdZTx82hbc/Xf4K/tZOOXSCkMvU4pKioRXGDLJRn0GM7Upe7kR721yg==", + "dev": true, + "peer": true + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true + }, + "is-number-object": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", + "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", + "dev": true, + "peer": true, + "requires": { + "has-tostringtag": "^1.0.0" + } + }, + "is-regex": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + } + }, + "is-set": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.2.tgz", + "integrity": "sha512-+2cnTEZeY5z/iXGbLhPrOAaK/Mau5k5eXq9j14CpRTftq0pAJu2MwVRSZhyZWBzx3o6X795Lz6Bpb6R0GKf37g==", + "dev": true, + "peer": true + }, + "is-shared-array-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz", + "integrity": "sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2" + } + }, + "is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true + }, + "is-string": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", + "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "dev": true, + "peer": true, + "requires": { + "has-tostringtag": "^1.0.0" + } + }, + "is-symbol": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", + "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "dev": true, + "peer": true, + "requires": { + "has-symbols": "^1.0.2" + } + }, + "is-typed-array": { + "version": "1.1.10", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.10.tgz", + "integrity": "sha512-PJqgEHiWZvMpaFZ3uTc8kHPM4+4ADTlDniuQL7cU/UDA0Ql7F70yGfHph3cLNe+c9toaigv+DFzTJKhc2CtO6A==", + "dev": true, + "peer": true, + "requires": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0" + } + }, + "is-weakmap": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.1.tgz", + "integrity": "sha512-NSBR4kH5oVj1Uwvv970ruUkCV7O1mzgVFO4/rev2cLRda9Tm9HrL70ZPut4rOHgY0FNrUu9BCbXA2sdQ+x0chA==", + "dev": true, + "peer": true + }, + "is-weakset": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.2.tgz", + "integrity": "sha512-t2yVvttHkQktwnNNmBQ98AhENLdPUTDTE21uPqAQ0ARwQfGeQKRVS0NNurH7bTf7RrvcVn1OOge45CnBeHCSmg==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.1" + } + }, + "isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "peer": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "jest-diff": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.3.1.tgz", + "integrity": "sha512-vU8vyiO7568tmin2lA3r2DP8oRvzhvRcD4DjpXc6uGveQodyk7CKLhQlCSiwgx3g0pFaE88/KLZ0yaTWMc4Uiw==", + "dev": true, + "peer": true, + "requires": { + "chalk": "^4.0.0", + "diff-sequences": "^29.3.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + }, + "dependencies": { + "ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true + }, + "pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "requires": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + } + }, + "react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + } + } + }, + "jest-get-type": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.2.0.tgz", + "integrity": "sha512-uXNJlg8hKFEnDgFsrCjznB+sTxdkuqiCL6zMgA75qEbAJjJYTs9XPrvDctrEig2GDow22T/LvHgO57iJhXB/UA==", + "dev": true, + "peer": true + }, + "jest-matcher-utils": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.3.1.tgz", + "integrity": "sha512-fkRMZUAScup3txIKfMe3AIZZmPEjWEdsPJFK3AIy5qRohWqQFg1qrmKfYXR9qEkNc7OdAu2N4KPHibEmy4HPeQ==", + "dev": true, + "peer": true, + "requires": { + "chalk": "^4.0.0", + "jest-diff": "^29.3.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + }, + "dependencies": { + "ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true + }, + "pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "requires": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + } + }, + "react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + } + } + }, + "jest-message-util": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.3.1.tgz", + "integrity": "sha512-lMJTbgNcDm5z+6KDxWtqOFWlGQxD6XaYwBqHR8kmpkP+WWWG90I35kdtQHY67Ay5CSuydkTBbJG+tH9JShFCyA==", + "dev": true, + "peer": true, + "requires": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.3.1", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "dependencies": { + "ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true + }, + "pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "peer": true, + "requires": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + } + }, + "react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "peer": true + } + } + }, + "jest-util": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.3.1.tgz", + "integrity": "sha512-7YOVZaiX7RJLv76ZfHt4nbNEzzTRiMW/IiOG7ZOKmTXmoGBxUDefgMAxQubu6WPVqP5zSzAdZG0FfLcC7HOIFQ==", + "dev": true, + "peer": true, + "requires": { + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + } + }, + "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, + "peer": true + }, + "jsonc-parser": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.0.tgz", + "integrity": "sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==", + "dev": true, + "peer": true + }, + "kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true + }, + "local-pkg": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.4.2.tgz", + "integrity": "sha512-mlERgSPrbxU3BP4qBqAvvwlgW4MTg78iwJdGGnv7kibKjWcJksrG3t6LB5lXI93wXRDvG4NpUgJFmTG4T6rdrg==", + "dev": true + }, + "locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "requires": { + "p-locate": "^5.0.0" + } + }, + "lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true, + "peer": true + }, + "loupe": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", + "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", + "dev": true, + "peer": true, + "requires": { + "get-func-name": "^2.0.0" + } + }, + "lz-string": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.4.4.tgz", + "integrity": "sha512-0ckx7ZHRPqb0oUm8zNr+90mtf9DQB60H1wMCjBtfi62Kl3a7JbHob6gA2bC+xRvZoOL+1hzUK8jeuEIQE8svEQ==", + "dev": true, + "peer": true + }, + "magic-string": { + "version": "0.26.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.26.7.tgz", + "integrity": "sha512-hX9XH3ziStPoPhJxLq1syWuZMxbDvGNbVchfrdCtanC7D13888bMFow61x8axrx+GfHLtVeAx2kxL7tTGRl+Ow==", + "dev": true, + "requires": { + "sourcemap-codec": "^1.4.8" + } + }, + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "peer": true, + "requires": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + } + }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true + }, + "min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "peer": true + }, + "mlly": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.1.0.tgz", + "integrity": "sha512-cwzBrBfwGC1gYJyfcy8TcZU1f+dbH/T+TuOhtYP2wLv/Fb51/uV7HJQfBPtEupZ2ORLRU1EKFS/QfS3eo9+kBQ==", + "dev": true, + "peer": true, + "requires": { + "acorn": "^8.8.1", + "pathe": "^1.0.0", + "pkg-types": "^1.0.1", + "ufo": "^1.0.1" + }, + "dependencies": { + "pathe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.0.0.tgz", + "integrity": "sha512-nPdMG0Pd09HuSsr7QOKUXO2Jr9eqaDiZvDwdyIhNG5SHYujkQHYKDfGQkulBxvbDHz8oHLsTgKN86LSwYzSHAg==", + "dev": true, + "peer": true + } + } + }, + "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 + }, + "nanoid": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", + "integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==", + "dev": true + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true + }, + "npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "requires": { + "path-key": "^3.0.0" + } + }, + "object-inspect": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.2.tgz", + "integrity": "sha512-z+cPxW0QGUp0mcqcsgQyLVRDoXFQbXOwBaqyF7VIgI4TWNQsDHrBpUQslRmIfAoYWdYzs6UlKJtB2XJpTaNSpQ==", + "dev": true, + "peer": true + }, + "object-is": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", + "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "peer": true + }, + "object.assign": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", + "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + } + }, + "onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "requires": { + "yocto-queue": "^0.1.0" + } + }, + "p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "requires": { + "p-limit": "^3.0.2" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "pathe": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-0.2.0.tgz", + "integrity": "sha512-sTitTPYnn23esFR3RlqYBWn4c45WGeLcsKzQiUpXJAyfcWkolvlYpV8FLo7JishK946oQwMFUCHXQ9AjGPKExw==", + "dev": true, + "peer": true + }, + "pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "peer": true + }, + "picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, + "picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true + }, + "pkg-types": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.0.1.tgz", + "integrity": "sha512-jHv9HB+Ho7dj6ItwppRDDl0iZRYBD0jsakHXtFgoLr+cHSF6xC+QL54sJmWxyGxOLYSHm0afhXhXcQDQqH9z8g==", + "dev": true, + "peer": true, + "requires": { + "jsonc-parser": "^3.2.0", + "mlly": "^1.0.0", + "pathe": "^1.0.0" + }, + "dependencies": { + "pathe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.0.0.tgz", + "integrity": "sha512-nPdMG0Pd09HuSsr7QOKUXO2Jr9eqaDiZvDwdyIhNG5SHYujkQHYKDfGQkulBxvbDHz8oHLsTgKN86LSwYzSHAg==", + "dev": true, + "peer": true + } + } + }, + "postcss": { + "version": "8.4.21", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.21.tgz", + "integrity": "sha512-tP7u/Sn/dVxK2NnruI4H9BG+x+Wxz6oeZ1cJ8P6G/PZY0IKk4k/63TDsQf2kQq3+qoJeLm2kIBUNlZe3zgb4Zg==", + "dev": true, + "requires": { + "nanoid": "^3.3.4", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + } + }, + "pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "peer": true, + "requires": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "dependencies": { + "ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "peer": true + } + } + }, + "prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "requires": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + } + }, + "react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "peer": true + }, + "readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "requires": { + "picomatch": "^2.2.1" + } + }, + "redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "dev": true, + "peer": true, + "requires": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + } + }, + "regenerator-runtime": { + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", + "dev": true, + "peer": true + }, + "regexp.prototype.flags": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.4.3.tgz", + "integrity": "sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "functions-have-names": "^1.2.2" + } + }, + "resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "dev": true, + "requires": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + } + }, + "rollup": { + "version": "2.79.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.1.tgz", + "integrity": "sha512-uKxbd0IhMZOhjAiD5oAFp7BqvkA4Dv47qpOCtaNvng4HBwdbWtdOh8f5nZNuk2rp51PMGk3bzfWu5oayNEuYnw==", + "dev": true, + "requires": { + "fsevents": "~2.3.2" + } + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dev": true, + "peer": true, + "requires": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + } + }, + "signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true + }, + "slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "peer": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "peer": true + }, + "source-map-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", + "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "dev": true + }, + "source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "peer": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "dev": true + }, + "stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "dev": true, + "peer": true, + "requires": { + "escape-string-regexp": "^2.0.0" + } + }, + "strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true + }, + "strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "dev": true, + "peer": true, + "requires": { + "min-indent": "^1.0.0" + } + }, + "strip-literal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-1.0.0.tgz", + "integrity": "sha512-5o4LsH1lzBzO9UFH63AJ2ad2/S2AVx6NtjOcaz+VTT2h1RiRvbipW72z8M/lxEhcPHDBQwpDrnTF7sXy/7OwCQ==", + "dev": true, + "peer": true, + "requires": { + "acorn": "^8.8.1" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "peer": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true + }, + "tinybench": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.3.1.tgz", + "integrity": "sha512-hGYWYBMPr7p4g5IarQE7XhlyWveh1EKhy4wUBS1LrHXCKYgvz+4/jCqgmJqZxxldesn05vccrtME2RLLZNW7iA==", + "dev": true, + "peer": true + }, + "tinypool": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-0.3.0.tgz", + "integrity": "sha512-NX5KeqHOBZU6Bc0xj9Vr5Szbb1j8tUHIeD18s41aDJaPeC5QTdEhK0SpdpUrZlj2nv5cctNcSjaKNanXlfcVEQ==", + "dev": true, + "peer": true + }, + "tinyspy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-1.0.2.tgz", + "integrity": "sha512-bSGlgwLBYf7PnUsQ6WOc6SJ3pGOcd+d8AA6EUnLDDM0kWEstC1JIlSZA3UNliDXhd9ABoS7hiRBDCu+XP/sf1Q==", + "dev": true, + "peer": true + }, + "to-regex-range": { + "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, + "requires": { + "is-number": "^7.0.0" + } + }, + "type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "peer": true + }, + "ufo": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.0.1.tgz", + "integrity": "sha512-boAm74ubXHY7KJQZLlXrtMz52qFvpsbOxDcZOnw/Wf+LS4Mmyu7JxmzD4tDLtUQtmZECypJ0FrCz4QIe6dvKRA==", + "dev": true, + "peer": true + }, + "vite": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-3.2.5.tgz", + "integrity": "sha512-4mVEpXpSOgrssFZAOmGIr85wPHKvaDAcXqxVxVRZhljkJOMZi1ibLibzjLHzJvcok8BMguLc7g1W6W/GqZbLdQ==", + "dev": true, + "requires": { + "esbuild": "^0.15.9", + "fsevents": "~2.3.2", + "postcss": "^8.4.18", + "resolve": "^1.22.1", + "rollup": "^2.79.1" + } + }, + "vite-node": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-0.27.0.tgz", + "integrity": "sha512-O1o9joT0qCGx5Om6W0VNLr7M00ttrnFlfZX2d+oxt2T9oZ9DvYSv8kDRhNJDVhAgNgUm3Tc0h/+jppNf3mVKbA==", + "dev": true, + "peer": true, + "requires": { + "cac": "^6.7.14", + "debug": "^4.3.4", + "mlly": "^1.0.0", + "pathe": "^0.2.0", + "picocolors": "^1.0.0", + "source-map": "^0.6.1", + "source-map-support": "^0.5.21", + "vite": "^3.0.0 || ^4.0.0" + } + }, + "vite-plugin-imba": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/vite-plugin-imba/-/vite-plugin-imba-0.10.1.tgz", + "integrity": "sha512-L4YKjsg5h5PPJRmLFw/68beerBRzCGiSjCqe0Xxh1aavvcAL57ZgT+7Y2kvwG7rcFO1YBdWtJ/tyJEsMK7rEAg==", + "dev": true, + "requires": { + "@rollup/pluginutils": "^4.2.1", + "cross-env": "^7.0.3", + "debug": "^4.3.4", + "deepmerge": "^4.2.2", + "diff": "^5.1.0", + "kleur": "^4.1.5", + "magic-string": "^0.26.2" + }, + "dependencies": { + "kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true + } + } + }, + "vitest": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-0.27.0.tgz", + "integrity": "sha512-BnOa7T6CnXVC6UgcAsvFOZ2Dtvqkt+/Nl6CRgh4qVT70vElf65XwEL6zMRyTF+h2QXJziEkxYdrLo5WCxckMLQ==", + "dev": true, + "peer": true, + "requires": { + "@types/chai": "^4.3.4", + "@types/chai-subset": "^1.3.3", + "@types/node": "*", + "acorn": "^8.8.1", + "acorn-walk": "^8.2.0", + "cac": "^6.7.14", + "chai": "^4.3.7", + "debug": "^4.3.4", + "local-pkg": "^0.4.2", + "picocolors": "^1.0.0", + "source-map": "^0.6.1", + "strip-literal": "^1.0.0", + "tinybench": "^2.3.1", + "tinypool": "^0.3.0", + "tinyspy": "^1.0.2", + "vite": "^3.0.0 || ^4.0.0", + "vite-node": "0.27.0" + } + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "dev": true, + "peer": true, + "requires": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + } + }, + "which-collection": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.1.tgz", + "integrity": "sha512-W8xeTUwaln8i3K/cY1nGXzdnVZlidBcagyNFtBdD5kxnb4TvGKR7FfSIS3mYpwWS1QUCutfKz8IY8RjftB0+1A==", + "dev": true, + "peer": true, + "requires": { + "is-map": "^2.0.1", + "is-set": "^2.0.1", + "is-weakmap": "^2.0.1", + "is-weakset": "^2.0.1" + } + }, + "which-typed-array": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.9.tgz", + "integrity": "sha512-w9c4xkx6mPidwp7180ckYWfMmvxpjlZuIudNtDf4N/tTAUB8VJbX25qZoAsrtGuYNnGw3pa0AXgbGKRB8/EceA==", + "dev": true, + "peer": true, + "requires": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.0", + "is-typed-array": "^1.1.10" + } + }, + "yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..db89943 --- /dev/null +++ b/package.json @@ -0,0 +1,16 @@ +{ + "name": "slots", + "version": "0.0.0", + "type": "module", + "scripts": { + "start": "vite", + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "devDependencies": { + "imba": "^2.0.0-alpha.226", + "vite": "^3.2.5", + "vite-plugin-imba": "^0.10.1" + } +} diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..e6824ab --- /dev/null +++ b/src/index.js @@ -0,0 +1 @@ +import "./main.imba" \ No newline at end of file diff --git a/src/main.imba b/src/main.imba new file mode 100644 index 0000000..9ed9a1d --- /dev/null +++ b/src/main.imba @@ -0,0 +1,50 @@ +global css @root ff:Arial c:white/87 bg:black/85 +global css a c:indigo5 c@hover:indigo6 +global css body m:0 d:flex ja:center h:100vh + +tag app-counter + count = 0 + "Count is {count}" + + # css without a selector applies to the enclosing element + css d:inline-block user-select:none cursor:pointer fs:6 bg:gray9 + p:2.5 5 m:6 bd:1px solid transparent rd:4 tween:border-color 250ms + bc@hover:indigo5 + +tag app + + # inline styles with square brackets + + + # this css applies to nested svg elements and not parents + css img h:23 p:1.5em + transition:transform 250ms, filter 250ms + @hover transform:scale(1.1) + filter:drop-shadow(0 0 4em red5) + + + + + + css filter@hover:drop-shadow(0 0 4em white7) + + <[d:inline-block transform:rotateY(180deg)]> + + + "Imba + Vite" + + + + css p c:warm1 ws:pre + css a td:none +

+ "Check out our documentation at " + "Imba.io" + "." +

+ "Take the free Imba course on " + + "Scrimba.com" + "." + +imba.mount diff --git a/vite.config.js b/vite.config.js new file mode 100644 index 0000000..06e3bdf --- /dev/null +++ b/vite.config.js @@ -0,0 +1,7 @@ +import { imba } from 'vite-plugin-imba'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + base: '', + plugins: [imba()], +});